如何返回每个选中复选框的ID?

时间:2019-03-15 21:19:59

标签: javascript jquery html5 dom

我试图获取每个已选中复选框的ID,并将其存储在数组中。这是以下代码:

<html>
<head></head>
<title>checkbox test</title>
<body>
    <input type="checkbox" class="hello" id="123">1</input>
    <input type="checkbox" class="hello" id="456">2</input>
    <input type="checkbox" class="hello" id="789">3</input>
    <button onclick="Test()">Click</button>
</body>

<script>

    function Test() {
    let numbers = $('.hello:checkbox:checked').each(() => {
        let checked = [];
        checked.push($(this).attr('id'));

        return checked;
    });

    console.log(numbers);
    // OUTPUT WHEN CHECKBOXES 2 AND 3 ARE CHECKED:
    // [input#456.hello, input#789.hello, prevObject: w.fn.init(1)]

    // EXPECTED OUTPUT WHEN 2 AND 3 ARE CHECKED:
   //  [456, 789]
}



</script>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
</html>

如果我只是简单地键入:$('.hello:checkbox:checked').attr('id');,我将得到选中的第一个复选框的ID,但是当我运行循环时,我得到的是带有以下格式的元素的数组:{ {1}}。如何运行循环,使其返回已选中复选框的ID(,仅ID )?

0 个答案:

没有答案