动态插入的HTML在我的表元素中呈现为文本

时间:2017-03-11 06:53:51

标签: javascript html5

module_name

2 个答案:

答案 0 :(得分:2)

您的尖括号与HTML中的标记名称之间不能有空格。

这就是为什么你的字符串< i class = "Small material - icons" > supervisor_account < /i>被错误地解析了。它应该写成:

<i class = "Small material - icons" > supervisor_account </i>

<小时/>

演示片段:

&#13;
&#13;
function addUser() {

  var userLogo = '<i class = "Small material - icons" > supervisor_account </i>';

  var user = document.getElementById('name').value;
  var email = document.getElementById('email').value;

  if (!user || !email) {
    alert("Error");
  } else {

    var table = document.getElementsByTagName('table')[0];
    var newRow = table.insertRow(1);

    var cel0 = newRow.insertCell(0);
    var cel1 = newRow.insertCell(1);
    var cel2 = newRow.insertCell(2);

    cel0.innerHTML = userLogo;
    cel1.innerHTML = user;
    cel2.innerHTML = email;
  }

}

addUser()
&#13;
table td, table th { padding: 0.5em; }
&#13;
<input id="name" value="John Doe">
<input id="email" value="john.doe@example.com">
<table>
  <th>Icon</th>
  <th>Name</th>
  <th>Email</th>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

插入的html上有不必要的空格

&#13;
&#13;
       function addUser() {

            var userLogo = '<i class="Small material - icons"> supervisor_account </i>';

            var user = document.getElementById('name').value;
            var email = document.getElementById('email').value;;

            if (!user || !email) {
                alert("Error");
            } else {

                var table = document.getElementsByTagName('table')[0];
                var newRow = table.insertRow(1);

                var cel0 = newRow.insertCell(0);
                var cel1 = newRow.insertCell(1);
                var cel2 = newRow.insertCell(2);

                cel0.innerHTML = userLogo;
                cel1.innerHTML = user;
                cel2.innerHTML = email;
            }

        }
&#13;
table {
    border-collapse: collapse;
}

table, th, td {
    border: 1px solid black;
}
&#13;
Name <input type='text' id='name'/>
email <input type='text' id='email'>
<button type='button' onclick="addUser()">addUser</button>
<table>
<tr>
<td>cel0</td>
<td>cel1</td>
<td>cel2</td>
</tr>
</table>
&#13;
&#13;
&#13;