2014-09-01 66 views
0

我想添加一個select(下拉列表)到我表中的每一行。 該表使用JavaScript創建,並具有使用JQuery從xml文件導入的動態內容。 我管理成功導入所有內容,但下拉列表僅顯示在最後一行。 我會appriciate如果你們可以幫助我在每一行都有下拉。 非常感謝!Javascript select table cell

下面是僅用空白選擇的代碼提取(導入的內容存儲在這些元素中)。所有輸出如「行」僅用於測試目的。 「Numrows」也用於測試目的。

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" lang="en"> 
<head> 
    <meta charset="utf-8" > 

    <title>table select test</title> 
</head> 
<body> 

    <table id="scrolltable"> 
    </table> 

<script type="text/javascript"> 
    var tabbody = document.getElementById("scrolltable"); 

    var types = document.createElement("select"); 
    var units = document.createElement("select"); 

    parseTable(3, types, "row ", units); 

    function parseTable(numrows, types, limits, units) { 
     for (i = 0; i < numrows; i++) { 
      var row = document.createElement("tr"); 
      var cell1 = document.createElement("td"); 
      cell1.style.width="300px"; 
      cell1.appendChild(types); 
      row.appendChild(cell1); 
      var cell2 = document.createElement("td"); 
      cell2.innerHTML = limits + i; 
      cell2.style.width = "100px"; 
      row.appendChild(cell2); 
      var cell3 = document.createElement("td"); 
      cell3.appendChild(units); 
      row.appendChild(cell3); 
      tabbody.appendChild(row); 
     } 
    } 
</script> 
</body> 
</html> 

回答

0

沒有最低例如,它可能是難以確定的問題,但我的猜測是:

你只是你的循環之前創建的類型和單位元素,讓你在追加相同的對象並且每次將其中一個添加到單元格中時,都會將其從原始單元格中取出並放入新單元格中。這就是「appendChild」所做的,它不克隆元素,它使用同一個(http://www.w3schools.com/jsref/met_node_appendchild.asp)。

如果您在您的每一步新的選擇元素,你應該罰款=)

+1

非常感謝你。將聲明移入循環確實解決了問題。 – Otto 2014-09-01 14:16:00

0

typesunits定義一次,所以它們是單一元素。所以他們被移動到你上次調用appendChild的地方。如果您想查看會發生什麼情況,請在結束for循環之前嘗試添加alert('');,並查看每行的操作。

如果你想將其添加每一行,然後你在每個itterration需要新的實例:

function parseTable(numrows, types, limits, units) { 
    for (i = 0; i < numrows; i++) { 
     var row = document.createElement("tr"); 
     var cell1 = document.createElement("td"); 
     cell1.style.width="300px"; 
     types = document.createElement("select"); 
     cell1.appendChild(types); 
     row.appendChild(cell1); 
     var cell2 = document.createElement("td"); 
     cell2.innerHTML = limits + i; 
     cell2.style.width = "100px"; 
     row.appendChild(cell2); 
     var cell3 = document.createElement("td"); 
     units = document.createElement("select"); 
     cell3.appendChild(units); 
     row.appendChild(cell3); 
     tabbody.appendChild(row); 
    } 
} 
+0

非常感謝。 – Otto 2014-09-01 14:16:25