為什麼for循環重複輸出相同的記錄?JavaScript (Why for loop output same record repeatedly? JavaScript)


問題描述

為什麼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 divs 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.

(by NikolaSaet.niese)

參考文件

  1. Why for loop output same record repeatedly? JavaScript (CC BY‑SA 2.5/3.0/4.0)

#for-loop #jquery #javascript #frontend






相關問題

從R中的類引用列表中獲取類引用字段的最小值 (Get min value of a class reference field from a list of class references in R)

在 SQL Server 2008 中運行 WHILE 或 CURSOR 或兩者 (Running WHILE or CURSOR or both in SQL Server 2008)

danh sách trong python, vòng lặp for, mảng (list in python, loop for, array)

如何編寫一個程序來自動執行一組查詢 (How to write a procedure to execute set of queries automatically)

xPath 在使用 for-each 循環變量時找不到選擇器,但可以正常工作 (xPath not finding selector when using for-each loop variable, but works otherwise)

為什麼for循環重複輸出相同的記錄?JavaScript (Why for loop output same record repeatedly? JavaScript)

在 for 循環中將參數傳遞給 setTimeout (Passing argument to setTimeout in a for loop)

使用python匹配條件後如何從列表的開始迭代開始for循環 (How to start for-loop from the starting iteration of list after matching the condition using python)

BASH:在 for 循環中使用 continue (BASH: Using a continue in a for loop)

如何識別 For / Select / Loop 中的行號 (How do I identify the row number in a For / Select / Loop)

如何循環遍歷列表中的項目不斷附加在循環中的列表? (how to loop through a list where the items of the list are constantly appended in the loop?)

是否可以僅使用 for 循環來實現包含 for 循環的遞歸函數,該循環包含對上述函數的調用? (Can a recursive function containing a for loop that contains a call of the mentioned function be implemented using only for loops?)







留言討論