Home  >  Article  >  Web Front-end  >  Usage examples of prop() method in jQuery_jquery

Usage examples of prop() method in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:22:021307browse

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

This method can get or set the attribute value of the matching element.
The effects vary depending on the method parameters.

Grammar structure 1:
When the parameter is an attribute name, this method can match the attribute value of the first matching element with the specified attribute name in the element collection.

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

Parameter list:

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

实例代码:

实例一:

复制代码 代码如下:






prop()函数-脚本之家






     

  •  

  


以上代码可以返回被选中的checkbox的属性值。

实例代码二:

复制代码 代码如下:






prop()函数-脚本之家






     
  • 脚本之家欢迎您

  •  

  •  

  


以上代码中,由于li元素集合中第一个li元素并没有id属性,所以返回值为空。

语法结构二:

以属性的“名/值对”对象方式设置所有匹配元素的属性值。

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

Parameter list:

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

实例代码:

实例一:

复制代码 代码如下:






prop()函数-脚本之家






     

  •  

  


以上代码能够将选中所有复选框。

实例二:

复制代码 代码如下:






prop()函数-脚本之家






 

欢迎来到脚本之家



以上代码可以设置td的宽度和高度。

语法三:

以属性名/值对方式设置所有匹配元素的属性值。

复制代码 代码如下:
$(selector).prop(key,value)

Parameter list:

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

实例代码:

复制代码 代码如下:






prop()函数-脚本之家





脚本之家欢迎您




以上代码可以为div设置指定的样式。

语法结构四:

通过函数返回值设置属性值。

复制代码 代码如下:
$(selector).prop(name,function(index,oldvalue))

Parameter list:

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

实例代码:

复主代码 代码如下:






prop()函数-脚本之家