Javascript 为什么单击复选框不会添加属性 checked='checked'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4882000/
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
Why clicking on checkbox does not add the attribute checked='checked'
提问by felix
When I click a checkbox, why does checked attribute is not getting added?. You can see the code here
http://jsfiddle.net/FCrSg/
当我单击一个复选框时,为什么没有添加已选中的属性?。你可以在这里看到代码
http://jsfiddle.net/FCrSg/
采纳答案by PetersenDidIt
What are you trying to do? Find out if its checked?
你想做什么?看看它是否被检查?
$('.user_roles').click(function(){
console.log( $(this).is(':checked'));
});
回答by David Tang
The HTML attributechecked
means: checked by default, when the page loads. This won'tchange when the checkbox is clicked.
在HTML属性checked
方法:检查默认情况下,页面加载时。单击复选框时,这不会改变。
<input type="checkbox" checked="checked"> <!-- The HTML attribute -->
The DOM propertychecked
is actually the current state of the checkbox and is either true/false. This willchange when the checkbox is clicked, but isn't visible when you inspect the HTML.
该DOM属性checked
实际上是复选框的当前状态,要么是真/假。单击复选框时,这将更改,但在检查 HTML 时不可见。
$('input:check')[0].checked == true;
// Whether or not the checkbox is currently checked
回答by user113716
If you want to see it appear on the element displayed in the console, use the native setAttribute()
method.
如果您想看到它出现在控制台中显示的元素上,请使用本机setAttribute()
方法。
Example:http://jsfiddle.net/FCrSg/2/
示例:http : //jsfiddle.net/FCrSg/2/
this.setAttribute('checked',this.checked);
So it would look like this:
所以它看起来像这样:
$('.user_roles').click(function(){
this.setAttribute('checked',this.checked);
console.log( $(this) );
});
Then the console should give you:
然后控制台应该给你:
<input class=?"user_roles" type=?"checkbox" checked=?"true">?
Though you normally wouldn't need the attribute set like that. Typically the property is enough.
尽管您通常不需要这样设置的属性。通常属性就足够了。