jQuery中的"attr()"方法设置样式却没有效果

使用jQuery的同学可能会遇到这个问题,在页面上写的attr()方法却没有作用。先看一段jQuery官网的解释:

.attr() versus .prop()

jQuery 1.6 introduced the .prop() method for setting or getting properties on nodes and deprecated the use of .attr() to set properties. However, versions up to 1.9 continued to support using .attr() for specific situations. This behavior in the name of backwards compatibility causes confusion when selectors are used that distinguish between attributes and properties.

For example, boolean attributes such as checked and disabled on a checkbox are affected by this change. The correct behavior of "input[checked]" is to select checkboxes that have a checked attribute, regardless of its string value, and regardless of their current state. In contrast, "input:checked" selects checkboxes that are currently checked as reflected in their boolean (true or false) checked property, which is affected when the user clicks the box for example. Versions prior to 1.9 sometimes do not select the correct nodes with these selectors.

Here are some examples of correct usage when setting checked on a checkbox; the same rules apply for disabled. Note that only the property consistently reflects and updates the current state of the checkbox across all browsers; rarely will you need to set the attribute.

// Correct if changing the attribute is desired
$(elem).attr("checked", "checked");
// Correct for checking the checkbox
$(elem).prop("checked", true);
// Correct if removing the attribute is desired (rare)
$(elem).removeAttr("checked");
// Correct for clearing the checkbox
$(elem).prop("checked", false);

 

The value property versus attribute on input elements is another example of this ambiguity. The attribute generally reflects the value that was read from the HTML markup; the property reflects the current value. Since the .val() method is the recommended jQuery way to get or set the values of form elements, this confusion usually does not affect users.

However, when a selector like "input[value=abc]" is used, it should always select by the value attribute and not any change made to the property by the user, for example from them typing into a text input. As of jQuery 1.9, this behaves correctly and consistently. Earlier versions of jQuery would sometimes use the property when they should have used the attribute.

The jQuery Migrate plugin restores the old attribute-vs-property rules.

jQuery官网给出了解释,在jQuery1.6中用prop()代替attr()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值