我需要使用输入标记复选框来获取所有不重复的可能组合。这是我正在处理的代码:
$('#triggerEv').on('click', function () {
var firstTblItems = $("#firstTbl").find("input[type='checkbox']:checked"),
secondTblItems = $("#secondTbl").find("input[type='checkbox']:checked"),
i = 0,
j = 0,
itemsArr = [],
currPair;
for (i; i < firstTblItems.length; i++) {
for (j; j < secondTblItems.length; j++) {
currPair = firstTblItems.eq(i).val() + '_' + secondTblItems.eq(j).val();
if (itemsArr.indexOf(currPair) === -1) {
itemsArr.push(currPair);
}
}
}
console.log(itemsArr);
});
在这种情况下,如果你检查所有这些,右输出应该是:
itemsArr = [
"1_1",
"1_2",
"1_3",
"1_4",
"2_1",
"2_2",
"2_3",
"2_4",
];
采取文字应该是这样的:
Item 1 - Item 1
Item 1 - Item 2
Item 1 - Item 3
Item 1 - Item 4
Item 2 - Item 1
Item 2 - Item 2
Item 2 - Item 3
Item 2 - Item 4
但我得到了这个:
itemsArr = ["1_1", "1_2", "1_3", "1_4"];
哪个错误,我可以获得一些代码帮助吗? Here是玩弄的小提琴。
答案 0 :(得分:2)
您每次都没有重新初始化j
循环。在第一个外循环之后,j
永远停留在secondTblItems.length
,因此内循环永远不会再次运行。
只需更正循环初始化,替换:
for (i; i < firstTblItems.length; i++) {
for (j; j < secondTblItems.length; j++) {
使用:
for (i = 0; i < firstTblItems.length; i++) {
for (j = 0; j < secondTblItems.length; j++) {
$('#triggerEv').on('click', function() {
var firstTblItems = $("#firstTbl").find("input[type='checkbox']:checked"),
secondTblItems = $("#secondTbl").find("input[type='checkbox']:checked"),
i,
j,
itemsArr = [];
for (i = 0; i < firstTblItems.length; i++) {
for (j = 0; j < secondTblItems.length; j++) {
var currPair = firstTblItems.eq(i).val() + '_' + secondTblItems.eq(j).val();
if (itemsArr.indexOf(currPair) === -1) {
itemsArr.push(currPair);
}
}
}
console.log(itemsArr);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>First table</div>
<table width="100%" border="1" cellpadding="0" cellspacing="0" id="firstTbl">
<tr>
<td>
<input type="checkbox" name="manufacturer[]" id="man-1" value="1" />
</td>
<td>Item 1</td>
</tr>
<tr>
<td>
<input type="checkbox" name="manufacturer[]" id="man-2" value="2" />
</td>
<td>Item 2</td>
</tr>
<tr>
<td>
<input type="checkbox" name="manufacturer[]" id="man-5" value="3" />
</td>
<td>Item 3</td>
</tr>
<tr>
<td>
<input type="checkbox" name="manufacturer[]" id="man-4" value="4" />
</td>
<td>Item 4</td>
</tr>
</table>
<div>Second table</div>
<table width="100%" border="1" cellpadding="0" cellspacing="0" id="secondTbl">
<tr>
<td>
<input type="checkbox" name="branch[]" id="branch-1" value="1" />
</td>
<td>Item 1</td>
</tr>
<tr>
<td>
<input type="checkbox" name="branch[]" id="branch-2" value="2" />
</td>
<td>Item 2</td>
</tr>
<tr>
<td>
<input type="checkbox" name="branch[]" id="branch-5" value="3" />
</td>
<td>Item 3</td>
</tr>
<tr>
<td>
<input type="checkbox" name="branch[]" id="branch-4" value="4" />
</td>
<td>Item 4</td>
</tr>
</table>
<div>Result table</div>
<table width="100%" border="1" cellpadding="0" cellspacing="0" id="resultTbl"></table>
<button id="triggerEv">Combine values</button>
&#13;