$(this).checked 未选中复选框 [英] $(this).checked not picking up checked boxes

查看:40
本文介绍了$(this).checked 未选中复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能没有正确选择复选框(如果选中)使用此功能:

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 语句:

If I don't have the if statement:

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.

谢谢

推荐答案

正如其他答案所说,.checked 不适用于 jQuery 对象.

As the other answers say, .checked will not work on a jQuery object.

这样更容易形象化:

$(this).checked 返回 undefined/error,因为它是一个 jQuery 对象,而不是一个元素.
$(this)[0].checked 返回 checked 的值,因为您引用的是元素本身,而不是引用元素的 jQuery 对象.

$(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.

以下是您的脚本的修改和固定版本,完全消除了对 checkedvalue 使用 jQuery,因为它们是 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.

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

这篇关于$(this).checked 未选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆