問題描述
為什麼for循環重複輸出相同的記錄?JavaScript (Why for loop output same record repeatedly? JavaScript)
我有一些測試數據:
var $data = {
"pitanje": [{
"id": 1,
"naziv": 'Kako se zove najveci bruger',
"odgovori": [{
"id": "1",
"ime": "burger1",
"tip": "netacno"
}, {
"id": "2",
"ime": "burger2",
"tip": "netacno"
}, {
"id": "3",
"ime": "burger3",
"tip": "tacno"
}, {
"id": "4",
"ime": "burger4",
"tip": "netacno"
}]
}, {
"id": 2,
"naziv": 'Kako se zove najveci bruger king',
"odgovori": [{
"id": "1",
"ime": "burger12",
"tip": "netacno"
}, {
"id": "2",
"ime": "burger13",
"tip": "netacno"
}, {
"id": "3",
"ime": "burger14",
"tip": "tacno"
}],
}]
};
FOR ‑ LOOP:
for (var i = 0; i < $data.pitanje.length; i++) {
$("#kviz").append("<div class='pitanje col‑md‑12'><h1>" + $data.pitanje[i]['naziv'] + "</h1></div>");
for (var x = 0; x < $data.pitanje[i]['odgovori'].length; x++) {
$(".pitanje").append("<li class='odgovor col‑md‑3'><div data‑pitanjeid=" +
$data.pitanje[i]['id'] +
" data‑odgovorid=" +
$data.pitanje[i]['odgovori'][x]['id'] +
">" +
$data.pitanje[i]['odgovori'][x]['ime'] +
"</div></li>");
// console.log($data.pitanje[i]['odgovori'][x]);
};
};
輸出:
‑‑Kako se zove najveci bruger‑‑
burger1
burger2
burger3
burger4
**burger12**
**burger13**
**burger14**
(為什麼第二個循環中的這三個也在第一個)
*Kako se zove najveci bruger king*
burger12
burger13
burger14
參考解法
方法 1:
The problem is that every append one div element with the class pitanje
for every iteration of your outer loop:
$("#kviz").append("<div class='pitanje col‑md‑12'><h1>" + $data.pitanje[i]['naziv'] + "</h1></div>");
In the inner loop you query for $(".pitanje")
. In the the second iteration of the first loop this will find both div
s you have created, and will add the append the data to both of them.
You would need to write something like that:
for (var i = 0; i < $data.pitanje.length; i++) {
var elementToAppendTo = $("<div class='pitanje col‑md‑12'><h1></h1><ul></ul></div>");
elementToAppendTo.find('h1').text($data.pitanje[i]['naziv']);
$("#kviz").append(elementToAppendTo);
for (var x = 0; x < $data.pitanje[i]['odgovori'].length; x++) {
var newItem = $("<li class='odgovor col‑md‑3'><div></div></li>")
newItem.find('div').data({
pitanjeid: $data.pitanje[i]['id'],
odgovorid: $data.pitanje[i]['odgovori'][x]['id']
}).text($data.pitanje[i]['odgovori'][x]['ime'])
elementToAppendTo.find('ul').append(newItem);
// console.log($data.pitanje[i]['odgovori'][x]);
}
}
An additional note: a li
element is not a valid child of an ul
.