gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:46 24 4
gpt4 key购买 nike

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

$('#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>');

但我需要在不使用 jQuery 的情况下完成它。我怎样才能将它转换为仅 native 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";

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

最佳答案

如果不需要支持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>'
);

但是caniuse says即 IE8 和 IE9

(Throw) an "Invalid target element for this operation." error when called on a table, tbody, thead, or tr element.

当您插入 tr 时与 td在里面,我假设你是在 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);

关于javascript - 使用js将HTML代码附加到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33888266/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com