![](/img/trans.png)
[英]how to add font awesome icon to a button dynamically using javascript and html?
[英]How to dynamically add a font awesome Icon with javascript?
我有一個表,我已將其設置為使用按鈕動態添加行。我在弄清楚如何動態添加字體真棒圖標到末尾時遇到了一些問題。
下面是添加表格行的代碼。 它會根據需要添加前四個單元格,但如果您要成為 FA 圖標,我需要第 5 個單元格。
var insertRow = document.getElementById("addRow");
insertRow.onclick = function() {
var x = document.getElementById("myTable");
var row = x.insertRow(x.rows.length);
var cell = row.insertCell(0);
var a = document.createElement("input");
a.setAttribute("type","text");
a.setAttribute("class","billInfo");
cell.appendChild(a);
var cell1 = row.insertCell(1);
var b = document.createElement("input");
b.setAttribute("type","number");
b.setAttribute("class","billAmt");
b.setAttribute("onkeyup","calc(this)");
cell1.appendChild(b);
var cell2 = row.insertCell(2);
var c = document.createElement("input");
c.setAttribute("type","date");
c.setAttribute("class","date");
cell2.appendChild(c);
var cell3 = row.insertCell(3);
var d = document.createElement("input");
d.setAttribute("type","text");
d.setAttribute("class","commentBox");
cell3.appendChild(d);
var cell4 = row.insertCell(4);
var e = document.createElement("h5");
e.setAttribute("class","sourceText");
e.append('<i class="fa fa-trash-o" aria-hidden="true"></i>');
e.addEventListener("click", removeRow);
e.addEventListener("click", calc);
cell4.appendChild(e);
}
正如您在單元格 row4 中看到的那樣,它使用 h5 元素創建了 td,然后我創建了一個類,然后嘗試附加它,但是在添加表格行時,它只顯示附加后括號中的代碼。
我發現這段代碼可以獨立工作,但不確定如何將它與我的代碼結合起來。 它在帶有 onclick 類 sourceText 的 h1 元素旁邊添加了 FA 圖標。
function pronounce() {
$('h1.sourceText').append('<i class="fa fa-trash-o" aria-hidden="true">
</i>');
};
只需嘗試交換e.append('<i class="fa fa-trash-o" aria-hidden="true"></i>');
經過
e.innerHTML = '<i class="fa fa-trash-o" aria-hidden="true"></i>';
這應該正確呈現您的圖標。 您只是附加了一些未解析為 HTML 的文本。
看起來append
是這一行的罪魁禍首e.appendChild('<i class="fa fa-trash-o" aria-hidden="true"></i>');
使用appendChild
e.appendChild('<i class="fa fa-trash-o" aria-hidden="true"></i>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.