循环浏览页面上所有选中的复选框并将id拉入数组不起作用

Looping through all checked checkboxes on page and pulling id into array not working

本文关键字:复选框 id 不起作用 数组 浏览 循环      更新时间:2023-09-26

更新

我现在已经解决了这个问题,更改了这一行:

   idList.push(this.id);

至:

 $(this).attr('id') 

我试图循环浏览页面上的所有复选框,并将所有被选中的ID添加到数组中。我让它在每个复选框中循环,并检测它是否被选中,但我在将每个被选中复选框的ID添加到数组中时遇到了问题。

有人能告诉我哪里出了问题吗?

谢谢。

Javascript:

if (element == 'deleteButton' || element == 'allowButton')
            {
                //For testing.
                    //alert("Button Clicked");
                //Create an empty array, so it can be re-sized at run time.
                var idList = [];
                //Loop through all checkboxes, adding each ones id to an array. 
                $('#reported_rages').find('input[type="checkbox"]:checked').each(function () {
                   //this is the current checkbox   
                    //For testing.
                        //alert("Checked");
                    //Add the current ID to the array
                    idList.push(this.id);
                });
                //return false; // or do something else.
            }
            alert(idList);

这里尝试实现这些想法。

JSFiddle

/*sets variable to global so it can be accessed outside of function*/
var idList = [];
function run(){
    /*clears the original variable*/
    idList = [];
    $('#data').find('input[type="checkbox"]:checked').each(function () {
        idList.push(this.id);
    });
    /*prints after list is populated*/
    console.log(idList);
    $('#results').html(idList);
}
/*binds run function to click of submit*/
$('#submit').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='data'>
    <input id='1' type='checkbox' />
    <input id='2' type='checkbox' />
    <input id='3' type='checkbox' />
    <input id='4' type='checkbox' />
    <input id='5' type='checkbox' />
</div>
<div id='results'></div>
<button id='submit'>Submit</button>