jQuery中attr()和prop()的区别与使用

版权声明:wuyujin1997 reserve all rights. https://blog.csdn.net/wuyujin1997/article/details/88896098

API

  • attr()系列

    • attr(attributeName) 读取第一个匹配到的元素的指定属性值。
    • attr(attributeName, value) 设置单个指定的属性值。
    • attr(attributes) 设置多个。
    • attr(attributeName, func) func为function(index, thisAttr)
  • prop()系列

    • prop(propertyName)
    • prop(propertyName, value)
    • prop(properties)
    • prop(propertyName, func) func为function(index, thisProp)

API较为简单,主要是区分使用。
boolean attribute及其规范取值
Attribute和Property的区别

使用

可用的三个方法(读取属性的boolean值):

e.checked
$(e).is(":checked")
$(e).prop("checked")

不可用的方法$(e).attr("checked"),与复选框状态无关,只与checked是否在HTML标签中出现有关。
若不出现(无论复选框状态是否选中),返回undefined
checked在HTML开始标签中出现(无论复选框是否选中),返回checked
(只要checked在开始标签中出现,值为何已经不重要了)。

HTML & test

<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>attr prop test</title>
	<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
	<script>
		$(showMsg);
		function showMsg() {
			$("input").change(function () {
				var inputTest = $(this);
				$("p").html(`
					this.checked    = <b> ${this.checked} </b> <br>
					is(":checked")  = <b> ${inputTest.is(":checked")} </b> <br>
					prop("checked") = <b> ${inputTest.prop("checked")} </b><br>
					attr("checked") = <b> ${inputTest.attr("checked")} </b><br>
					`);
			}).change();
		}
	</script>
	<style>
		b {color: red}
	</style>
</head>
<body style="text-align:center">
	<input id="checkTest" type="checkbox" checked="checked">
	<!-- <input id="checkTest" type="checkbox" checked="随便的字符串依旧是checked"> -->
	<!-- <input id="checkTest" type="checkbox"> -->
	<label for="checkTest">test</label>

	<!-- checked在开始标签出现(无论取值为何):attr()取值为checked;
		不出现:attr()取值为undefined。 -->

	<p></p>
</body>
</html>

测试结果:
<input>标签中出现checked属性(无论字符串值为何):
在这里插入图片描述
在这里插入图片描述
删除<input>元素的checked属性:
在这里插入图片描述
在这里插入图片描述

attr()prop()的区别

Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.
注意:attribute的值是字符串(有些例外,如valuetabindex)。

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. 
To retrieve and change DOM properties such as the checked, selected, or disabled 
state of form elements, use the .prop() method.

从jQuery1.6开始,对那些一开始没有设置值的attribute,使用attr()方法会返回undefined
为了查询和改变DOM properties(如checked, selected, disabled等表单元素)的状态,应该使用prop()方法。

Attributes vs. Properties

The difference between attributes and properties can be important in specific situations. 
Before jQuery 1.6, the .attr() method sometimes took property values into account 
when retrieving some attributes, which could cause inconsistent behavior. 
As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, 
while .attr() retrieves attributes.

在特定情况下attributeproperty的不同之处会很重要。
在jQuery1.6之前,当用attr()查询一些attrbute时,也会查到一些property的值,这可能导致行为不一致。
从jQuery1.6开始,prop()提供显式的、用于专门查询property值的方法。而attr()查询attribute

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected 
should be retrieved and set with the .prop() method. 
Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. 
These do not have corresponding attributes and are only properties.

比如 selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, defaultSelected等应该用prop()方法检索和修改。
在jQuery1.6之前,这些properties也可以使用attr()方法检索,不过这些并不在attribute范围内。
这些都没有相应的attribute,他们只是properties
感觉:attribute可以有多种多样类型|格式的值,而property只是一种“是否”的属性值,boolean类型

Concerning boolean attributes, consider a DOM element defined by the HTML markup 
    <input type="checkbox" checked="checked" />
    and assume it is in a JavaScript variable named e:

关于boolean propertie,考虑用HTML定义好的一个DOM元素:
<input type="checkbox" checked="checked">,假定其JS变量名为e

e.checked - true (布尔值)将随复选框状态而变化
$(e).prop("checked") - true (布尔值)将随复选框状态而变化
e.getAttribute("checked") - checked (字符串)复选框的初始状态,不会改变。
$(e).attr("checked") (1.6) - checked (字符串)复选框的初始状态,不会改变。
$(e).attr("checked") (1.61+) - checked (字符串)将随复选框状态而变化。
$(e).attr("checked") (pre-1.6) - true (布尔值)已更改为复选框状态。

为保险,用prop()访问值为boolean类型的property

According to the W3C forms specification, the checked attribute is a boolean attribute, 
which means the corresponding property is true if the attribute is present at all—even if, 
for example, the attribute has no value or is set to empty string value or even "false". 
This is true of all boolean attributes.

根据W3C规范,该checked attribute是一个boolean attribute
这意味着只要设置了这个attribute,他的property值就是true,即使设置的值为"false"或空串""
所有boolean attribute都是如此。

只要显式的设置了boolean attribute的值,其properrty值就为true。设置了就是true

Nevertheless, the most important concept to remember about the checked attribute 
is that it does not correspond to the checked property. 
The attribute actually corresponds to the defaultChecked property 
and should be used only to set the initial value of the checkbox. 
The checked attribute value does not change with the state of the checkbox, while the checked property does. 
Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:

if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )

The same is true for other dynamic attributes, such as selected and value.

不过,关于checked attribute需要记住的最重要的一点是:他并不对应checked properrty
实际上,checked attribute对应的是defaultChecked property(即默认|初始的选中状态)
并且checkced attribute只应该用于设置复选框的初始值。
复选框的状态改变,并不会改变checked attribute,而checked property会改变。
因此,检查复选框是否选中的跨浏览器兼容的正确方法是使用以下的properrty

if (e.checkced)
if ($(e).prop("checked"))
if ($(e).is(":checked"))

其他的dynamic attribute也是如此,比如说selectedvalue

Additional Notes:
In Internet Explorer prior to version 9, using .prop() to set a DOM element property 
to anything other than a simple primitive value (number, string, or boolean) can cause memory leaks 
if the property is not removed (using .removeProp()) before the DOM element is removed from the document. 
To safely set values on DOM objects without memory leaks, use .data().

补充说明:
在IE9之前的版本中,如果还没有使用removeProp()移除property
就用prop()去设置一个DOM元素的值为非简单原始值(number, string, bolean)的类型,会导致内存泄漏。
为了安全地设置DOM对象而不导致内存泄漏,推荐使用data()

附:官方文档

The .attr() method gets the attribute value for only the first element in the matched set.
To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.

Using jQuery's .attr() method to get the value of an element's attribute has two main benefits:

Convenience: It can be called directly on a jQuery object and chained to other jQuery methods.
Cross-browser consistency: The values of some attributes are reported inconsistently across browsers, 
and even across versions of a single browser.
The .attr() method reduces such inconsistencies.
Note: Attribute values are strings with the exception of a few attributes such as value and tabindex.

As of jQuery 1.6
the .attr() method returns undefined for attributes that have not been set.
To retrieve and change DOM properties such as the checked
selected, or disabled state of form elements, use the .prop() method.

Attributes vs.
Properties
The difference between attributes and properties can be important in specific situations.
Before jQuery 1.6, the .attr() method sometimes took property values into account 
when retrieving some attributes, which could cause inconsistent behavior.
As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, 
while .attr() retrieves attributes.

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 
and defaultSelected should be retrieved and set with the .prop() method.
Prior to jQuery 1.6, these properties were retrievable with the .attr() method, 
but this was not within the scope of attr.
These do not have corresponding attributes and are only properties.

Concerning boolean attributes, consider a DOM element defined by the HTML markup 
<input type="checkbox" checked="checked" />, and assume it is in a JavaScript variable named elem:

elem.checked	true (Boolean) Will change with checkbox state
$( elem ).prop( "checked" )	true (Boolean) Will change with checkbox state
elem.getAttribute( "checked" )	"checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6)	"checked" (String) Initial state of the checkbox; does not change
$( elem ).attr( "checked" ) (1.6.1+)	"checked" (String) Will change with checkbox state
$( elem ).attr( "checked" ) (pre-1.6)	true (Boolean) Changed with checkbox state

According to the W3C forms specification, the checked attribute is a boolean attribute, 
which means the corresponding property is true if the attribute is present at all—even if, 
for example, the attribute has no value or is set to empty string value or even "false".
This is true of all boolean attributes.

Nevertheless, the most important concept to remember about the checked attribute 
is that it does not correspond to the checked property.
The attribute actually corresponds to the defaultChecked property 
and should be used only to set the initial value of the checkbox.
The checked attribute value does not change with the state of the checkbox, while the checked property does.
Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property:

if ( elem.checked )
if ( $( elem ).prop( "checked" ) )
if ( $( elem ).is( ":checked" ) )
The same is true for other dynamic attributes, such as selected and value.

Additional Notes:
In Internet Explorer prior to version 9, using .prop() to set a DOM element property to anything other 
than a simple primitive value (number, string, or boolean) can cause memory leaks 
if the property is not removed (using .removeProp()) before the DOM element is removed from the document.
To safely set values on DOM objects without memory leaks, use .data().

猜你喜欢

转载自blog.csdn.net/wuyujin1997/article/details/88896098