javascript内部的push方法.每个循环只返回一个数组

javascript .push method inside .each loop only returning one array

本文关键字:返回 数组 一个 循环 内部 push 方法 javascript      更新时间:2023-09-26

我正在尝试迭代复选框组,如果每个组至少有一个复选框被选中,我想将该产品信息添加到数组(upperOrder)中。我的代码的问题是,它只添加了最后一个选中的复选框组(或者重写了之前添加的组)。

基本上,我想要一个多维数组,主数组是upperOrder,子数组是每个产品的信息。

感谢并感谢任何人的帮助,或者如果有更好的方法来实现这一点,我将感谢任何建议!

html:

<form class="upperCheckboxForm" data-prodid="100" data-prodname="adams" id="group1">
<fieldset data-role="controlgroup">
    <legend>Group 1:</legend>
    <input type="checkbox" name="checkbox-v-2a" id="checkbox-v-2a" value="one" data-tooth-position="UR1">
    <label for="checkbox-v-2a">One</label>
    <input type="checkbox" name="checkbox-v-2b" id="checkbox-v-2b" value="two" data-tooth-position="UR2">
    <label for="checkbox-v-2b">Two</label>
    <input type="checkbox" name="checkbox-v-2c" id="checkbox-v-2c" value="three" data-tooth-position="UR3">
    <label for="checkbox-v-2c">Three</label>
</fieldset>
</form>
<form class="upperCheckboxForm" data-prodid="101" data-prodname="lap" id="group2">
<fieldset data-role="controlgroup">
    <legend>Group 2:</legend>
    <input type="checkbox" name="checkbox-v-2a" id="checkbox-v-2a" value="four" data-tooth-position="UR4">
    <label for="checkbox-v-2a">Four</label>
    <input type="checkbox" name="checkbox-v-2b" id="checkbox-v-2b" value="five" data-tooth-position="UR5">
    <label for="checkbox-v-2b">Five</label>
    <input type="checkbox" name="checkbox-v-2c" id="checkbox-v-2c" value="six" data-tooth-position="UR6">
    <label for="checkbox-v-2c">Six</label>
</fieldset>
</form>
<button id="submitPrintForm">Click</button>

jquery:

$('#submitPrintForm').on('click', function() {
var upperOrder      = [];
$('.upperCheckboxForm').each(function() {
    var $prodName           = $(this).data('prodname'),
        $prodId         = $(this).data('prodid'),
        $prodUrl            = $(this).attr('id'),
        $prodPosition       = [];
    $('#'+ $prodUrl +' input:checked').each(function() {
      $prodPosition.push($(this).data('tooth-position'));
    })
    if($prodPosition.length > 0) {
        upperOrder.push = ([$prodName, $prodId, $prodPosition.length, $prodPosition]);
    }
})
console.log(upperOrder);
});

push是一个方法。这样称呼它:

upperOrder.push([$prodName, $prodId, $prodPosition.length, $prodPosition])

当您为upperOrder.push分配一些东西时,实际上是在覆盖方法push,这将导致对它的后续调用失败。

这就是你要找的吗?

$('#submitPrintForm').on('click', function() {
var upperOrder      = [];
$('.upperCheckboxForm').each(function() {
    var $prodName           = $(this).data('prodname'),
        $prodId         = $(this).data('prodid'),
        $prodUrl            = $(this).attr('id'),
        $prodPosition       = [];
    $('input:checked', this).each(function() {
      $prodPosition.push($(this).data('tooth-position'));
    })

    if($prodPosition.length > 0) {
        upperOrder.push($prodName, $prodId, $prodPosition.length, $prodPosition);
    }
})
    console.log(upperOrder);
});