Home > Web Front-end > JS Tutorial > body text

Usage examples of attr() method in jQuery_jquery

WBOY
Release: 2016-05-16 16:22:11
Original
1082 people have browsed it

The example in this article describes the usage of attr() method in jQuery. Share it with everyone for your reference. The specific analysis is as follows:

This method sets or returns the attribute value of the matching element.
The attr() method has different functions depending on the parameters.

Grammar structure 1:
Get the attribute value of the specified attribute of the first matching element.

Copy code The code is as follows:
$(selector).attr(name)

Parameter list:

参数 描述
name 定义要获取其值的属性名称。

Example code:

Copy code The code is as follows:






attr() function-Script Home





I am the first div

I am the second div




In the above code, clicking the button can pop up the class attribute value of the first element in the matching element collection.

Grammar structure 2:
Sets the attribute value for the specified attribute of the matching element.

Copy code The code is as follows:
$(selector).attr(attribute,value)

Parameter list:

参数 描述
attribute 定义要设置值的属性名称。
value 定义要设置的属性值。

实例代码:

复制代码 代码如下:






attr()函数-脚本之家





脚本之家欢迎您




以上代码中, 当点击按钮的时候,能够重新设置div元素的class属性值。

语法结构三:
将“名/值”形式的对象设置为匹配元素的属性。可以一次性设置多组“名/值”对,对匹配元素属性进行设置。

复制代码 代码如下:
$(selector).attr(properties)

参数列表:

参数 描述
attribute:value 定义属性名/值对

Example code:

Copy code The code is as follows:






attr() function-Script Home








Welcome to Script House




In the above code, you can set the width and height of the cell.

Syntax structure four: Set attribute values ​​through function return values.

Copy code The code is as follows:
$(selector).attr(name,function(index,oldvalue) )

Parameter list:

参数 描述
name 定义要设置值的属性的名称。
function(index,oldvalue) 定义返回属性值的函数
index - 可选,接受选择器的索引位置。
class - 可选,接受选择器的当前的属性值。

实例代码:

复主代码 代码如下:






attr()函数-脚本之家