jq1.6版本前后,attr()和prop()的区别,来自慕课网的回答

jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值时,会返回 property 的值,这就导致了结果的不一致。从 jQuery 1.6 开始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值。 

例如, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, 和 defaultSelected 应使用.prop()方法进行取值或赋值。 在jQuery1.6之前,这些属性使用.attr()方法取得,但是这并不是元素的attr属性。他们没有相应的属性(attributes),只有特性(property)。 

例如,考虑一个DOM元素的HTML标记中定义的<input type="checkbox" checked="checked" /> ,并假设它是一个JavaScript变量命名的elem : 

elem.checked true (Boolean) 将改变复选框的状态 
$(elem).prop("checked") true (Boolean) 将改变复选框的状态 
elem.getAttribute("checked") "checked" (String) 不会改变的复选框的初始状态; 
$(elem).attr("checked") (1.6) "checked" (String) 不会改变的复选框的初始状态; 
$(elem).attr("checked") (1.6.1+) "checked" (String) 将改变复选框的状态 
$(elem).attr("checked") (pre-1.6) true (Boolean) 将改变复选框的状态 
根据W3C的表单规范 ,在checked属性是一个布尔属性,这意味着只要该 attribute 存在,即使它没有值,或是一个空字符串,该属性对应的 property 就是 true。

 

更改后的代码如下:

<script type="text/javascript">

        $(function () {

            $("#allorno").click(function () {

                $("input[name='items']").prop("checked", $(this).prop("checked"));

            });

        });

</script>

——————————————————————

最后感谢慕课网的叫jacsong的这位网友

posted @ 2017-03-03 09:40  佟舟  阅读(211)  评论(0编辑  收藏  举报