0
我試圖創建一個存儲庫的概述,類似於GitHub顯示項目概述的方式,除了我希望我的動態更改的單個頁面上。Javascript動態地更改html表格
所以我想用基礎概述創建表,然後單擊不同的行顯示行內容(如果該行中的元素具有內容)。
這是我現在所擁有的,但我無法讓行獲得實際更新表的鏈接元素。如果我從控制檯調用該函數,它看起來好像工作正常,這只是我認爲需要幫助的鏈接。
JS:
var Table = document.createElement('table');
function updateTable(node) {
Table.innerHTML = "";
if (node.children !== undefined){
for (var i = 0; i < node.children.length; i++){
var tr = document.createElement('tr');
if (node.children[i].hasChildren){
var a = document.createElement('a');
a.setAttribute('onclick', "updateTable(" + node.children[i] + ")");
a.appendChild(document.createTextNode(node.children[i].name));
tr.appendChild(a);
} else {
tr.appendChild(document.createTextNode(node.children[i].name));
}
Table.appendChild(tr);
document.getElementById('table').appendChild(Table);
}
}
}
var node = {name:'a', parent: null, children:[], size:0, hasChildren:true};
var node11 = {name:'gsidfhuo', parent: node1, children:[], size:0, hasChildren:false};
var node12 = {name:'sdlj', parent: node1, children:[], size:0, hasChildren:false};
var node1 = {name:'aasdf', parent: node, children:[node11,node12], size:2, hasChildren:true};
node.children.push(node1);
var node2 = {name:'ahtrs', parent: node, children:[], size:0, hasChildren:false};
node.children.push(node2);
var node31 = {name:'gsidfhuo', parent: node1, children:[], size:0, hasChildren:false};
var node3 = {name:'aawsefd', parent: node, children:[node31], size:1, hasChildren:true};
node.children.push(node3);
var node4 = {name:'aikuyr', parent: node, children:[], size:0, hasChildren:false};
node.children.push(node4);
updateTable(node);
HTML:
<!doctype html>
<html lang='en'>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<div class="container">
<h1 class="txt"> Test Table</h1>
<font style="font-size:+3"><table id="table" border="1px" style="width:50%"></table></font>
</div>
<script src='App.js'></script>
</body>
</html>
好吧,我試過了,現在表格根本不起作用。從節點構建的初始表顯示節點31,節點3和節點4.如果點擊這些鏈接,它根本不會更新。查看瀏覽器中的元素,事件偵聽器也不會出現在鏈接中。我刪除了你提到的a.setAttribute,並用a.addEventListener('click',updateTable(node.children [i]))替換了它。 – Mas