jQuery-属性方法

时间:2020-02-23 14:46:12  来源:igfitidea点击:

在本教程中,我们将学习jQuery属性prop()方法。

prop()

我们使用prop()方法执行以下任务。

  • 设置属性值
  • 获取属性值

prop:设置属性值

要设置HTML元素的属性,我们将属性名称和值传递给prop()方法。

在以下示例中,我们将ID为" sample-input-checkbox1"的复选框输入字段的" checked"属性设置为" true"。

$("#sample-input-checkbox1").prop("checked", true);

我们还可以传递具有属性值对的普通对象来设置属性。

在下面的示例中,我们将ID为" sample-input-checkbox1"的输入复选框的checked属性设置为true。

$("#sample-input-checkbox1").prop({
  "checked" : true
});

设置属性值的另一种方法如下

$("#sample-input-checkbox1").prop("checked", function(i, val) {
  console.log("Index: " + i);
  console.log("Prev value of the property: " + val);

  //return the inverse value
  return !val;
});

上面的代码将打印示例输入复选框的索引和先前值,并且将返回与先前值相反的值。
因此,如果复选框的checked属性设置为true,则该函数将返回false,反之亦然。

如果选择了多个元素,则prop()方法可以为其设置值。

在以下示例中,我们有4个复选框元素,每个元素具有相同的类" sample-checkbox"。
默认情况下,我们使用prop()方法来选中所有复选框。

HTML

<input type="checkbox" class="sample-checkbox">Apple
<input type="checkbox" class="sample-checkbox">Mango
<input type="checkbox" class="sample-checkbox">Orange
<input type="checkbox" class="sample-checkbox">Pomegranate

jQuery

$(".sample-checkbox").prop({
  "checked" : true
});

prop:获取属性值

为了获得属性值,我们必须将属性名称传递给prop()方法。

在以下代码中,我们将打印出复选框的选中状态。
如果选中该复选框,则为true,否则为false。

console.log( $("#sample-input-checkbox1").prop("checked") );

如果选择了多个元素,则" prop()"方法将返回第一个选定方法的值。

在下面的示例中,我们有4个checkbox元素,但是控制台中仅打印了第一个复选框的属性。

HTML

<input type="checkbox" class="sample-checkbox" checked>Apple
<input type="checkbox" class="sample-checkbox">Mango
<input type="checkbox" class="sample-checkbox" checked>Orange
<input type="checkbox" class="sample-checkbox">Pomegranate

jQuery

console.log( $(".sample-checkbox").prop("checked") );

要打印所有复选框的选中值,我们必须使用each()方法。

$(".sample-checkbox").each(function(index, elem){
  console.log("Index: " + index);
  console.log( $(elem).prop("checked") );
});

上面的代码将遍历所有具有" sample-checkbox"类的元素(复选框),并打印其索引和checked属性的值。