当我这样做时:
col = document.createElement("div");
col.setAttribute("id", "col" + ii);
alert(document.getElementById("col" + ii));
警报显示为空。如何使setAttribute产生效果?
使用document.createElement
创建元素时,它会创建该元素,但不会将其添加到DOM中。要将其添加到DOM中,您必须对您希望新元素所在的元素使用appendChild
方法。
假设您想在body
的末尾添加新的div
。请尝试以下代码。
col = document.createElement("div");
col.setAttribute("id", "col" + ii);
document.body.appendChild(col)
alert(document.getElementById("col" + ii));