简体   繁体   English

如何不使用每个而访问复选框数组的第一个元素?

[英]How to access the first element of the checkbox array without using each?

I have a Jquery event that will collect the list of selected checkboxes and I am currently experimenting their behaviours by trying to access them 1 by 1. 我有一个Jquery事件,它将收集选定复选框的列表,并且我目前正在尝试通过1对其进行访问来尝试其行为。

$('#sub').click(function () {

    var cb = $("input[type='checkbox']:checked");
    var count = cb.length;

    alert(cb[0].prop('checked'));

    if (count == 0) {
        alert('No subjects selected');
        return false;
    } else {
        return confirm(count + " row(s) selected, proceed?");
    }
});

Accessing cb directly won't work for some reason. 由于某些原因,直接访问cb无效。

I need to do something like this : 我需要做这样的事情:

 cb.each(function (i) {
    alert($(this).prop('checked'));
});

But this will require me to loop through all of them when I only need the first element of the array, to see if it's true. 但是,当我只需要数组的第一个元素时,就需要遍历所有这些元素,以查看其是否正确。

Are there any methods and can someone tell me why my first approach didn't work? 有什么方法,有人可以告诉我为什么我的第一种方法行不通吗? I tried using for loop but no luck. 我尝试使用for loop但没有运气。

You can use eq() 您可以使用eq()

alert(cb.eq(0).prop('checked'));

or cb[0] will return dom object cb[0]将返回dom对象

alert(cb[0].checked);

Ref : https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/ 参考: https : //learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/

What you are trying to do is to check whether at least one item is selected, since cb has only checked items you can just check whether the set has atleast one item like 您要执行的操作是检查是否至少选择了一项,因为cb仅检查了一项,因此您只需检查该集合是否至少有一项就可以了

$('#sub').click(function () {
    var cb = $("input[type='checkbox']:checked");

    if (!cb.length) {
        alert('No subjects selected');
        return false;
    } else {
        return confirm(count + " row(s) selected, proceed?");
    }

This: 这个:

var cb = $("input[type='checkbox']:checked");

Doesn't return a single element, it potentially returns many. 不返回单个元素,而是可能返回多个元素。

This will target the first checked checkbox: 这将针对第一个选中的复选框:

var cb = $("input[type='checkbox']:checked:first");

This will target the first checkbox regardless of state: 这将针对第一个复选框,而不管其状态如何:

var cb = $("input[type='checkbox']:first");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM