以下是jqeury判斷checkbox是否選中的方法作彤,親測(cè)第一種和第二種有效淀衣,第三種如果沒有定義checked屬性昙读,報(bào)錯(cuò)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;
親測(cè)有效,可反復(fù)選中和不選中
jquery中:
- 重復(fù)點(diǎn)擊失效
//測(cè)試發(fā)現(xiàn)膨桥,第一次有效蛮浑,但是經(jīng)過一次選中和不選中之后唠叛,就無效了
if($('#allCache').is(':checked')){
$('#allCache').removeAttr("checked");
}else{
$('#allCache').attr("checked",true);
}
- 可重復(fù)操作
//可以重復(fù)操作
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);
}
總結(jié):
??? jquery中上面兩種方案涉及到attr和prop的區(qū)別。
先看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
: