0

i already have a form and a table and data from the form is added to the table but i'm trying to add a insertBefore function for my form but it doesn't work. could you please tell me what is wrong with my script?

function insertBefore(){
    var table = document.getElementById('table');
    var row = document.createElement('tr');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    td1.innerHTML = document.getElementById('name').value;
    td2.innerHTML = document.getElementById('address').value;
    td3.innerHTML = document.getElementById('email').value;
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    table.tBodies [0].insertBefore();
    }

Thanks.

4

2 回答 2

1

当你使用 时insertBefore,你必须告诉浏览器三件事:

  • A = 要插入的元素
  • B = 要插入的元素
  • C = 之前要插入的元素

它应该采用以下形式:

A.insertBefore(B, C)

例如:

document.body.insertBefore(table, document.body.firstChild)
于 2012-10-29T08:25:31.763 回答
0

如果您知道必须插入的元素始终是第一个元素,则可以使用 prepend() 代替。这将始终将您想要的元素添加为父元素的第一个子元素。

于 2012-10-29T08:35:04.547 回答