Javascript $(此项)。已选中但未选中复选框

Javascript $(此项)。已选中但未选中复选框,javascript,jquery,Javascript,Jquery,我有一个无法正确选取复选框的函数(如果选中) 使用此功能: function playerJson() { players = []; $('input[name=playerCheckList]').each(function () { if ($(this).checked) { players.push($(this).val()); } }); return $.toJSON(players); }

我有一个无法正确选取复选框的函数(如果选中) 使用此功能:

function playerJson() {
    players = [];
    $('input[name=playerCheckList]').each(function () {
        if ($(this).checked) {
            players.push($(this).val());
        }
    });

    return $.toJSON(players);
}
我使用此功能检查所有按钮(正确)

如果我没有If语句:

if ($(this).checked) 
从第一段代码中,它正确地拾取所有值(是否选中)

所以,这句话可能是问题所在,但我不知道为什么


感谢引用了一个jQuery对象,它没有“checked”属性(不过DOM会有该属性)。您需要获取属性值

$(this).prop("checked");
编辑:我支持vanilla.js是因为
vanilla.js
$(这个)。选中的
不起作用,因为
$(这个)
是一个jQuery项目

只需查看DOM对象的
checked
属性(
this
):


正如其他答案所说,
.checked
在jQuery对象上不起作用

通过这种方式更容易可视化:

$(this).checked
返回未定义/错误,因为它是jQuery对象,而不是元素。
$(this)[0]。checked
返回
checked
的值,因为您引用的是元素本身,而不是引用该元素的jQuery对象

下面是您的脚本的修改和固定版本,完全取消了对
checked
value
使用jQuery,因为它们是对jQuery的毫无意义的使用。另一个用法更有意义,因此它将保留在我的答案中

function playerJson() {
        players = [];
        $('input[name=playerCheckList]').each(function () {
            if (this.checked) {
                players.push(this.value);
            }
        });
        return $.toJSON(players);
    }

或者
$(this).is(':checked')
只是一个注释:
is()
prop()
稍慢(
attr()
是最慢的),并且都比香草慢。当然,
is()
仍然有效。@BlackSheep我没有使用jQuery:-P“$(this0[0]。checked返回checked的值),它不会抛出错误(不是downvoter)
...
if (this.checked) {
    players.push(this.value);
}
...
function playerJson() {
        players = [];
        $('input[name=playerCheckList]').each(function () {
            if (this.checked) {
                players.push(this.value);
            }
        });
        return $.toJSON(players);
    }