我有一个嵌套在
因此,HTML 结构如下,并且可以有多个带有
现在我需要构建一个对象,该对象将如下所示:
以下是示例内容,对象必须与此相似:
为了实现这个目标,我必须遍历每个
我试图做以下操作,但是
<ul>
/ <li>
列表中的复选框,其中父复选框具有 .check-negozio
类。在该父级内可能会有一些带有 .check-cassa
类的复选框,这些复选框可能包含其他用 .check-operatore
标记的子复选框。因此,HTML 结构如下,并且可以有多个带有
.check-negozio
的 <li>
。现在我需要构建一个对象,该对象将如下所示:
[{ negozio: npv, cassa: [{ cassa: cs, operatore: [] }] }]
以下是示例内容,对象必须与此相似:
[{ negozio: 0, cassa: [{ cassa: 1, operatore: [] }, { cassa: 5, operatore: [0]}] }]
为了实现这个目标,我必须遍历每个
.check-negozio
,然后在同一个循环中,我必须遍历该.check-negozio
的子元素.check-cassa
,如果.check-cassa
有子元素.check-operator
,则循环遍历它们。我试图做以下操作,但是
$(this).children(".check-cassa").each
似乎是错误的方法,因为它甚至不进入该循环... 我应该如何循环遍历嵌套元素?
$(".check-negozio").each(function() {
if (this.checked || this.indeterminate) { // if parent checkbox is checked add it to object
const npv = $(this).attr('data-npv');
selezione.negozio = npv;
$(this).children(".check-cassa").each(function() { // here i should loop throw children .check-cassa of .check-negozio
if (this.checked || this.indeterminate) { // if check-cassa is checked go ahead
const cs = $(this).attr('data-cs');
if ($(this).closest('li').has('ul').length) { // here i check if check-cassa contain any child (in this case check-operatore)
$(this).children(".check-operatore").each(function() { // if there are child check-operatore loop throw them
if (this.checked) { // if checked add data-op inside array of operatore
const op = $(this).attr('data-op');
operatore.push({
OP: op
});
}
})
selezione.cassa.push({
CS: cs,
OP: operatore
}) // here i add data-cs and array operatore inside object
} else { // else if there isn't any child check-operatore just add data-cs with empty array of operatore
selezione.cassa.push({
CS: cs,
OP: []
});
}
}
})
config.push(selezione); // adding created object inside array
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>
<input type="checkbox" class="check-negozio" data-npv="0">
<ul>
<li class="nav-item">
<input type="checkbox" class="check-cassa" data-cs="1">
</li>
<li>
<input type="checkbox" class="check-cassa" data-cs="5">
<ul>
<li>
<input type="checkbox" class="check-operatore" data-op="0">
</li>
</ul>
</li>
</ul>
</li>
</ul>
check_negozio
的元素是一个没有子元素的输入元素。check_cassa
和check_operatore
元素是li
和ul
的子元素。 - vqf