Javascript createElement() 在 Chrome 中不起作用

Rek*_*kha 3 javascript google-chrome

JavascriptcreateElement()在 Chrome 中不起作用,但在 IE 和 Firefox 中运行良好。为什么?

小智 6

var name = document.createElement("Div" ); 
Run Code Online (Sandbox Code Playgroud)

将工作。稍后您可以添加属性,例如

name.colSpan="2";
document.body.appendChild(name);
Run Code Online (Sandbox Code Playgroud)

注意:不要尝试使用像createElement("<div />"). 它在 Chrome 中不起作用。

编辑:修复了上述代码中的语法问题。应该有一个点而不是逗号。


Joh*_*ros 5

它运行良好,使用此代码:

var catDiv = document.createElement("div");
catDiv.innerHTML = "Test";
document.body.appendChild(catDiv);
Run Code Online (Sandbox Code Playgroud)

另一个工作示例(如果您的 HTML 中有一个 Id = myTableBody 元素)

var appendingTo = document.getElementById("myTableBody");
var tr = document.createElement("tr");
tr.setAttribute("name", "i");
appendingTo.appendChild(tr);
Run Code Online (Sandbox Code Playgroud)