jQuery之使用jQuery.fn.prop()替换jQuery.fn.attr()

来源:互联网 发布:java math.random 编辑:程序博客网 时间:2024/06/10 18:05

Check不能使用jQuery更改选中状态的处理解决方法

今天做WEB开发框架搭建写Examples时发现之前写过的JS-Table控件不能正常工作了。具体表现为在设置checkbox为选中状态时,checked=“checked”属性已经被设置进去了,但是checkbox状态实际为未选中,但是删除checked属性时会将checkbox的状态改变为未选中。检查代码后发现逻辑上并没有问题,使用FireBug测试也没有发现问题。

经过修改HTML的DOCTYPE,HTML标签的命名空间后测试同样不能通过。于是猜测问题可能出在jQuery方法调用上,控件中设置checked属性使用的是$checkbox.attr('checked','checked')这样的用法。该方法以前是可以使用的,但是现在不能用了,猜测可能是浏览器兼容问题,于是想检查一下jQuery有没有直接设置checkbox选中状态的方法。经过一番本地API查询并未找到。突然想到,新框架用的是jQuery 1.10.x的最新版,而我查询的API是1.5.x版的,于是打开jQuery官方网站的API页面查看了下Attribute目录下支持的方法,遂发现jQuery.fn.prop()方法,该方法的描述初看起来与attr方法一模一样,但是看到详细说明时却指出了其与attr方法的区别。

jQuery的prop方法更改的是DOM对象property,而attr更改的是HTML的attribute。经分析prop操作的应该是DOM的原生属性,而attr则是操作DOM的附加属性(用户添加的属性)。原生属性不能被删除,而附加属性则可以被删除。

下面是引起我关注的两段话:

The .prop() method is a convenient way to set the value of properties—especially when setting multiple properties, using values returned by a function, or setting values on multiple elements at once.It should be used when setting selectedIndex,tagName, nodeName, nodeType, ownerDocument,defaultChecked, or defaultSelected.Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include thevalue property of input elements, the disabled property of inputs and buttons, or thechecked property of a checkbox. The.prop() method should be used to set disabled and checked instead of the.attr() method. The.val() method should be used for getting and setting value.

第一段话说的是prop方法可以读取和设置DOM的属性,而在1.6版本后selectedIndex,tagName, nodeName, nodeType, ownerDocument,defaultChecked, or defaultSelected这些属性必须使用prop来设置。

第二段说的是DOM的property改变通常会在没有直接修改HTML的Attribute的情况下关联引起HTML的Attribute的变化。 在操作disabled、checked属性时应该使用prop()方法替代attr()方法。