当前位置: 首页 > 工具软件 > jQuery Xcolor > 使用案例 >

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

徐鑫鹏
2023-12-01

使用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()

 类似资料: