以下是jqeury判斷checkbox是否選中的方法,親測第一種和第二種有效,第三種如果沒有定義checked屬性,報錯undefind
alert($("#allCache").get(0).checked)
alert($('#allCache').is(':checked'))
alert ($('#allCache').attr('checked'))
選中和取消選中checkbox
javascript中:
- 取消選中
document.getElementById("allCache").checked = false; - 選中
document.getElementById("allCache").checked = true;
親測有效,可反復選中和不選中
jquery中:
- 重復點擊失效
//測試發現,第一次有效,但是經過一次選中和不選中之后,就無效了
if($('#allCache').is(':checked')){
$('#allCache').removeAttr("checked");
}else{
$('#allCache').attr("checked",true);
}
- 可重復操作
//可以重復操作
if($('#allCache').is(':checked')){
// document.getElementById("allCache").checked = false;
// $('#allCache').removeAttr("checked");
$("#allCache").prop('checked',false);
}else{
// document.getElementById("allCache").checked = true;
// $('#allCache').attr("checked",true);
$("#allCache").prop('checked',true);
}
總結:
??? jquery中上面兩種方案涉及到attr和prop的區別。
先看attr的解釋:Get the value of an attribute for the first element in the set of matched elements.
?? The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.
在看prop的解釋:Get the value of a property for the first element in the set of matched elements.
?? The .prop() method gets the property value for only the first element in the matched set. It returns undefined for the value of a property that has not been set, or if the matched set has no elements. To get the value for each element individually, use a looping construct such as jQuery's .each() or .map() method.
Attributes vs. Properties
The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr()
method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop()
method provides a way to explicitly retrieve property values, while .attr()
retrieves attributes.
For example, selectedIndex
, tagName
, nodeName
, nodeType
, ownerDocument
, defaultChecked
, and defaultSelected
should be retrieved and set with the [.prop()](http://api.jquery.com/prop/)
method. Prior to jQuery 1.6, these properties were retrievable with the .attr()
method, but this was not within the scope of attr
. These do not have corresponding attributes and are only properties.
Concerning boolean attributes, consider a DOM element defined by the HTML markup <input type="checkbox" checked="checked" />
, and assume it is in a JavaScript variable named elem
: