首页 > 语言 > JavaScript > 正文

jQuery 更改checkbox的状态,无效的解决方法

2024-05-06 14:54:29
字体:
来源:转载
供稿:网友

今天写页面遇到复选框动态全选或全不选问题,正常写法如下:

$("#tb").find("input[type='checkbox']").attr("checked","checked");

but!第一次点击全选按钮input显示对勾,第二次就不行了,查了下有建议用prop的,亲测有效。那两者有啥区别呢?

jQuery函数attr()和prop()的区别:

1、操作对象不同

“attr”和“prop”分别是单词“attribute”和“property”的缩写,并且它们均表示"属性"的意思。

不过,在jQuery中,“attribute”和“property”却是两个不同的概念。attribute表示HTML文档节点的属性,property表示JS对象的属性。

<!-- 这里的id、class、data_id均是该元素文档节点的attribute --><div id="message" class="test" data_id="123"></div><script type="text/javascript">// 这里的name、age、url均是obj的propertyvar obj = { name: "CodePlayer", age: 18, url: "http://www.365mini.com/" };</script>

在jQuery中,prop()函数的设计目标是用于设置或获取指定DOM元素(指的是JS对象,Element类型)上的属性(property);attr()函数的设计目标是用于设置或获取指定DOM元素所对应的文档节点上的属性(attribute)。

在jQuery的底层实现中,函数attr()和prop()的功能都是通过JS原生的Element对象(如上述代码中的msg)实现的。attr()函数主要依赖的是Element对象的getAttribute()和setAttribute()两个方法。prop()函数主要依赖的则是JS中原生的对象属性获取和设置方式。

<div id="message" class="test" data_id="123"></div><script type="text/javascript">var msg = document.getElementById("message");var $msg = $(msg);/* *** attr()依赖的是Element对象的element.getAttribute( attribute ) 和 element.setAttribute( attribute, value ) *** */// 相当于 msg.setAttribute("data_id", 145);$msg.attr("data_id", 145);// 相当于 msg.getAttribute("data_id");var dataId = $msg.attr("data_id"); // 145/* *** prop()依赖的是JS原生的 element[property] 和 element[property] = value; *** */// 相当于 msg["pid"] = "pid值";$msg.prop("pid", "pid值");// 相当于 msg["pid"];var testProp = $msg.prop("pid"); // pid值</script>

当然,jQuery对这些操作方式进行了封装,使我们操作起来更加方便(比如以对象形式同时设置多个属性),并且实现了跨浏览器兼容。

此外,虽然prop()针对的是DOM元素的property,而不是元素节点的attribute。不过DOM元素某些属性的更改也会影响到元素节点上对应的属性。例如,property的id对应attribute的id,property的className对应attribute的class

<div id="message" class="test" data_id="123"></div><script type="text/javascript">var msg = document.getElementById("message");var $msg = $(msg);document.writeln( $msg.attr("class") ); // test$msg.prop("className", "newTest");// 修改className(property)导致class(attitude)也随之更改document.writeln( $msg.attr("class") ); // newTest</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选