javascript jQuery接收复选框状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7645508/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:47:41  来源:igfitidea点击:

jQuery receiving checkbox status

javascriptjquerycheckbox

提问by Yekver

I'm changing checkbox status this way: $(this).attr("checked", 'checked');

我正在以这种方式更改复选框状态: $(this).attr("checked", 'checked');

After this I want to receive checkbox status, but I got this:

在此之后我想收到复选框状态,但我得到了这个:

$(this).attr('checked'): "checked"
$(this).is(':checked'): false

How this can be?

这怎么可能?

P.S. Maybe I'm not correctly changing checkbox status via jQuery?

PS 也许我没有通过 jQuery 正确更改复选框状态?

回答by ThiefMaster

The proper way is $(this).prop('checked')to return the boolean propertyinstead of the attribute (which is a a string).

正确的方法是$(this).prop('checked')返回布尔属性而不是属性(它是一个字符串)。

Using .prop()you can also setthe checked state: $(this).prop('checked', true_or_false);

使用.prop()您还可以设置选中状态:$(this).prop('checked', true_or_false);

As you can see on http://jsfiddle.net/ThiefMaster/QR2fL/, .attr('checked')returns the initial value of the attribute - it does not changed when checking/unchecking the checkbox.

正如您在http://jsfiddle.net/ThiefMaster/QR2fL/ 上看到的,.attr('checked')返回属性的初始值 - 在选中/取消选中复选框时它不会改变。

回答by Nicola Peluchetti

You should not check the checkbox like this:

你不应该像这样选中复选框:

$(this).attr("checked", 'checked');

but like this

但像这样

$(this).prop("checked", true);

To check if a checkbox is checked you can use:

要检查复选框是否被选中,您可以使用:

$(this).prop('checked');

or

或者

$(this).is(':checked');

which return a boolean proerty

它返回一个布尔属性