📜  jQuery prop()

📅  最后修改于: 2020-11-26 01:12:24             🧑  作者: Mango

jQuery prop()

jQuery prop()方法用于两个目的。

  • 它用于返回一组匹配元素中第一个元素的属性值。
  • 它用于为一组匹配的元素设置一个或多个属性值。

jQuery prop()方法通常用于检索属性值,例如DOM属性(例如tagName,nodeName,defaultChecked)或自己定制的属性。这是设置属性值(尤其是多个属性)的非常方便的方法。

如果要检索HTML属性,则应改用attr()方法。

removeProp()方法用于删除属性。

句法:

要返回属性的值:

$(selector).prop(property)

设置属性和值:

$(selector).prop(property,value)

要使用函数设置属性和值:

$(selector).prop(property,function(index,currentvalue))

设置多个属性和值:

$(selector).prop({property:value, property:value,...})

jQuery prop()方法的参数

Parameter Description
Property It specifies the name of the property.
Value It defines the value of the property.
Function(index, currentvalue) It specifies a function which returns the value of the property to set.
  • Index: It provides the index position of the element in the set.
  • Currentvalue: It provides the current property value of the selected element.

jQuery prop()方法的示例

我们来看一个简单的jQuery prop()方法示例。










jQuery prop()示例2

让我们看一下jQuery prop()方法的另一个示例。




  
  prop demo
  
  




jQuery attr()和jQuery prop()方法之间的区别:

这是一个非常常见的问题,因为大多数人对在哪里使用prop()方法和在哪里attr()方法感到困惑。它们之间的差异在特定情况下非常重要。

以下是它们之间的确切区别:

  • jQuery attr()方法用于检索HTML属性值,而jQuery prop()方法用于检索属性值。
  • attr()方法更改HTML标记的属性,而prop()方法根据DOM树更改HTML标记的属性。
  • 属性通常比属性更易于处理,因此大多数使用jQuery prop()方法而不是attr()方法。