javascript $(this).checked 不选中复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21123721/
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
$(this).checked not picking up checked boxes
提问by Sherman Szeto
I have a function that is not picking up checkboxes correctly (if checked) with this function:
我有一个功能无法正确选择复选框(如果选中),使用此功能:
function playerJson() {
players = [];
$('input[name=playerCheckList]').each(function () {
if ($(this).checked) {
players.push($(this).val());
}
});
return $.toJSON(players);
}
I use this function to check all buttons (correctly)
我使用此功能检查所有按钮(正确)
$(function () {
$("#checkAllPlayers").click(function () {
$('input[name=playerCheckList]').each(function () {
$(this).prop('checked', true);
});
});
});
If I don't have the if statement:
如果我没有 if 语句:
if ($(this).checked)
from the first piece of code, it correctly picks up all the values (checked or not)
从第一段代码开始,它正确地获取了所有值(检查与否)
So, this statement is probably the problem, but I'm not sure why.
所以,这个陈述可能是问题所在,但我不确定为什么。
Thanks
谢谢
回答by Sterling Archer
That is referring to a jQuery object, which has no property 'checked' (The DOM would have that property though). You need to get the attribute value.
那是指一个 jQuery 对象,它没有“检查”属性(尽管 DOM 会有该属性)。您需要获取属性值。
$(this).prop("checked");
Edit: I support qwertynl's answerbecause vanilla.js
编辑:我支持qwertynl 的回答,因为vanilla.js
回答by qwertynl
$(this).checked
does not work because $(this)
is a jQuery oject.
$(this).checked
不起作用,因为它$(this)
是一个 jQuery 对象。
Just look at the checked
attribute of the DOM object (this
):
看一下checked
DOM 对象的属性(this
):
...
if (this.checked) {
players.push(this.value);
}
...
回答by qwertynl
As the other answers say, .checked
will not work on a jQuery object.
正如其他答案所说,.checked
不适用于 jQuery 对象。
This is easier visualized this way:
这样更容易形象化:
$(this).checked
returns undefined/error because it is a jQuery object, not an element.$(this)[0].checked
returns the value of checked
because you are referencing the element itself, not the jQuery object referencing the element.
$(this).checked
返回 undefined/error 因为它是一个 jQuery 对象,而不是一个元素。$(this)[0].checked
返回 的值,checked
因为您正在引用元素本身,而不是引用元素的 jQuery 对象。
Below is a modified and fixed version of your script, eliminating the use of jQuery entirely for checked
and for value
as they are a pointless use of jQuery. The other use makes a little more sense, and so it will remain in my answer.
下面是你的脚本的修改和固定的版本,消除了对jQuery的使用完全是为了checked
和value
因为他们是一个毫无意义的使用jQuery的。另一种用法更有意义,因此它将保留在我的答案中。
function playerJson() {
players = [];
$('input[name=playerCheckList]').each(function () {
if (this.checked) {
players.push(this.value);
}
});
return $.toJSON(players);
}