以下是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 , and assume it is in a JavaScript variable named
elem
: