📜  jQuery attr()

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

jQuery attr()

jQuery attr()方法用于设置或返回所选元素的属性和值。

jQuery attr()方法有两种用法。

  • 返回属性值:此方法返回第一个匹配元素的值。
  • 设置属性值:此方法用于设置一组匹配元素的一个或多个属性/值对。

句法:

要返回属性的值:

$(selector).attr(attribute)

设置属性和值:

$(selector).attr(attribute,value)

通过使用函数来设置属性和值:

$(selector).attr(attribute,function(index,currentvalue))

设置多个属性和值:

$(selector).attr({attribute:value, attribute:value,...}) 

jQuery attr()方法的参数

Parameter Description
Attribute This parameter is used to specify the name of the attribute.
Value This parameter is used to specify the value of the attribute.
Function (index, currentvalue) It is a parameter to specify a function that returns an attribute value to set.
  • Index: It is used to receive the index position of the element in the set.
  • Currentvalue: It is used to provide the current attribute value of selected elements.

jQuery attr()方法的示例

让我们以一个示例来演示jQuery attr()方法。








Good Morning Friends

使用jQuery attr()方法的好处

它具有两个主要优点:

  • 便利性:当您使用jQuery attr()方法获取元素的属性值时,可以直接在jQuery对象上调用它并将其链接到其他jQuery方法。
  • 跨浏览器的一致性:您可以摆脱在不同浏览器甚至单个浏览器的不同版本上属性值的不一致更改。