如何使用javascript动态添加字体真棒图标?

Mar*_*ite 4 javascript font-awesome

我有一个表格,我将它设置为使用按钮动态添加行。我在弄清楚如何将字体真棒图标动态添加到最后时遇到了一些问题。

下面是添加表格行的代码。它根据需要添加前四个单元格,但如果您想成为 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);
 }
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,对于单元格 row4,它使用 h5 元素创建了 td,然后我创建了一个类,然后尝试追加它,但是在添加表格行时,它只显示追加后括号中的代码。

控制台视图

我发现这段代码可以独立工作,但不确定如何将它与我的代码结合起来。它使用 onclick 将 FA 图标添加到类 sourceText 的 h1 元素旁边。

 function pronounce() {  
  $('h1.sourceText').append('<i class="fa fa-trash-o" aria-hidden="true">
  </i>');
 };
Run Code Online (Sandbox Code Playgroud)

Mar*_*eib 6

只是一味的交换e.append('<i class="fa fa-trash-o" aria-hidden="true"></i>');通过

e.innerHTML = '<i class="fa fa-trash-o" aria-hidden="true"></i>';
Run Code Online (Sandbox Code Playgroud)

这应该正确呈现您的图标。您只是附加了一些未解析为 HTML 的文本。


Mut*_*ran 5

看起来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>');
Run Code Online (Sandbox Code Playgroud)

  • `appendChild` 不起作用。抛出错误 - `testbed-util.js:118 Uncaught TypeError: 无法在 'Node' 上执行 'appendChild': 参数 1 不是 'Node' 类型。`。[Mark Scheib](/sf/users/344490261/) 使用 `innerHTML` 的答案有效。 (2认同)