Jquery attr 方法为选中的复选框返回未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6528156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery attr method returns undefined for a checked checkbox
提问by Kaddy
For the above checkbox
对于上述复选框
document.getElementById("checkbox1").checked // -> returns true
But
但
var byAppr = document.getElementById('checkbox1').value;
$(byAppr).attr('checked') // -> returns undefined
I am testing this in firefox 3.6
我正在 Firefox 3.6 中测试这个
回答by ThiefMaster
Use one of the following:
使用以下方法之一:
$('#checkbox1').prop('checked')
- in jQuery 1.6+, usually the way to go$('#checkbox1').is(':checked')
- all jQuery versions, but slower$('#checkbox1').attr('checked')
- NOT in jQuery 1.6 - but in 1.6.1 and <=1.5, don't use it
$('#checkbox1').prop('checked')
- 在 jQuery 1.6+ 中,通常是要走的路$('#checkbox1').is(':checked')
- 所有 jQuery 版本,但速度较慢$('#checkbox1').attr('checked')
-不在jQuery 1.6 中 - 但在 1.6.1 和 <=1.5 中,不要使用它
Also, in cases where you already have the DOM element available directly (e.g. this
in an event handler bound to the field), use this.checked
instead of $(this)
with one of the methods above!
此外,如果您已经拥有直接可用的 DOM 元素(例如,this
在绑定到该字段的事件处理程序中),请使用上述方法之一this.checked
代替$(this)
!
回答by glortho
You're selecting based on value. I think you want:
您正在根据价值进行选择。我想你想要:
var byAppr = document.getElementById('checkbox1');
$(byAppr).attr('checked')