我搞不懂这件事。根据W3学校,选中的属性设置或返回复选框的选中状态。
那么,为什么$('input').checked ? $('div').slideDown() : $('div').slideUp();不能工作呢?
然而,使用道具确实有效。
$('input').prop('checked') ? $('div').slideDown() : $('div').slideUp();
这是根据数据库值选中的复选框。
发布于 2013-02-26 04:28:16
checked是一个DOM元素属性,所以在DOM元素上使用它而不是jQuery对象。
$('input')[0].checked如果您有一个jQuery对象,请使用prop而不是attr,因为您正在检查一个属性。作为参考:
$("<input type='checkbox' checked='checked'>").attr("checked") // "checked"
$("<input type='checkbox' checked='foo'>").attr("checked") // "checked"
$("<input type='checkbox' checked>").attr("checked") // "checked"
$("<input type='checkbox'>").attr("checked") // undefined而[0].getAttribute("checked")将返回实际值。
prop将根据属性是否存在返回true或false。
发布于 2013-02-26 04:27:52
checked是DOM对象的属性,而不是jQuery对象的属性。要使其工作,您必须获得DOM对象:
$('input')[0].checked;你也可以做.is(':checked')。
发布于 2013-02-26 05:04:30
在这种情况下,您需要的是prop()而不是attr(),在代码中用prop()替换对attr()的调用通常是可行的。
来自 http://blog.jquery.com/2011/05/10/jquery-1-6-1-rc-1-released/
属性和属性之间的差异在特定情况下可能很重要。在jQuery 1.6之前,.attr()方法有时会在检索某些属性时考虑属性值,这可能导致不一致的行为。从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性。
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)
此外,这个url将帮助您更多地了解查询.prop()与.attr()。
/is-checked-vs-attr-checked-checked/7在http://jsperf.com/is-checked-vs-attr-checked-checked/7上的一个区别
要理解The elements atttribute and properties,请参阅http://christierney.com/2011/05/06/understanding-jquery-1-6s-dom-attribute-and-properties/ http://jsperf.com/is-checked-vs-attr-checked-checked/7
https://stackoverflow.com/questions/15081335
复制相似问题