使用js将HTML代码附加到元素

Ami*_*emi 2 html javascript jquery

我有这个代码用于向现有表追加一行

$('#factorTable').append('<tr id="ft-' + id + '"><td id="ftn-' + id + '">' + name + '</td><td id="ftp-' + id + '">' + price + '</td><td id="ftNum-' + id + '">' + number + '</td><td id="ftSum-' + id + '">' + sum + '</td></tr>');
Run Code Online (Sandbox Code Playgroud)

但我需要在不使用jQuery的情况下完成它.如何将其转换为仅本机javascript我知道我可以使用以下代码向表中插入一行:

// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");

// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);

// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
Run Code Online (Sandbox Code Playgroud)

但是,正如你在我的jQuery代码中看到的,我需要添加id<td><tr>标签.

T.J*_*der 7

如果您不需要支持IE8或IE9,您可以使用insertAdjacentHTML:

document.getElementById('factorTable').insertAdjacentHTML(
    'beforeend',
    '<tr id="ft-' + id + '"><td id="ftn-' + id + '">' + name + '</td><td id="ftp-' + id + '">' + price + '</td><td id="ftNum-' + id + '">' + number + '</td><td id="ftSum-' + id + '">' + sum + '</td></tr>'
);
Run Code Online (Sandbox Code Playgroud)

caniuse说 IE8和IE9

(抛出)"此操作的目标元素无效".在table,tbody,thead或tr元素上调用时出错.

当你要插入一个trtd,它出现,我假设你在调用此tbody.

如果您需要IE9(或更早版本)支持,我们需要依靠createElement:

var tr = document.createElement('tr').
tr.id = 'ft-' + id;
tr.innerHTML = '<td id="ftn-' + id + '">' + name + '</td><td id="ftp-' + id + '">' + price + '</td><td id="ftNum-' + id + '">' + number + '</td><td id="ftSum-' + id + '">' + sum + '</td>';
document.getElementById('factorTable').appendChild(tr);
Run Code Online (Sandbox Code Playgroud)