如何使用JavaScript动态添加Font Awesome图标?

7
我有一个表格,并设置了动态添加行的按钮。我遇到了一些问题,不知道如何在末尾动态添加font awesome图标。
以下是添加表格行的代码。它会按需添加前四个单元格,但我需要第五个单元格成为FA图标。
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,然后我创建了一个类并尝试将其附加,但在添加表格行时,它只显示括号中的代码。

控制台视图

我发现这段代码可以单独使用,但不确定如何将其与我的代码结合起来。它在具有class sourceText的h1元素旁边添加FA图标,并具有onclick功能。

 function pronounce() {  
  $('h1.sourceText').append('<i class="fa fa-trash-o" aria-hidden="true">
  </i>');
 };
2个回答

9

只需尝试用以下代码替换 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。

那个可以运行,但是当尝试删除行时,它只会删除图标。不过我已经想通了。 - Mark White
@Marc Scheib,它不起作用。 document.createElement('span').innerHtml = '<i class="fa fa-trash-o" aria-hidden="true"></i>' 不起作用。 - Azhar Uddin Sheikh

4

看起来这一行的罪魁祸首是appende.appendChild('<i class="fa fa-trash-o" aria-hidden="true"></i>');

使用appendChild

e.appendChild('<i class="fa fa-trash-o" aria-hidden="true"></i>');

谢谢您的回复,但使用appendChild没有起作用。在控制台上折腾了一番后,我终于让它工作了。e.setAttribute("class","sourceText fa fa-trash-o"); $(e.sourceText).append('<i class="fa fa-trash-o"></i>');将fa fa-trash-o类添加到setAttribute中,并在下一行加上美元符号。 - Mark White
2
appendChild不起作用。抛出错误-testbed-util.js:118 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.Mark Scheib的答案使用innerHTML有效。 - Anish Sana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接