如何使用javascript向页面添加div?
所以。。。我想在文档的/body之前添加以下内容,但我似乎找不到使其正常工作的方法:如何使用javascript向页面添加div?,javascript,innerhtml,Javascript,Innerhtml,所以。。。我想在文档的/body之前添加以下内容,但我似乎找不到使其正常工作的方法: document.body.innerHTML+="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\""); document.body.innerHTML+=“response\”; 不要添加这样的内容!相反,请执行以下操作: var newDiv = document.create
document.body.innerHTML+="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\"");
document.body.innerHTML+=“response\”;
不要添加这样的内容!相反,请执行以下操作:
var newDiv = document.createElement('div')
newDiv.style.position = 'absolute'
newDiv.id = 'myDiv'
newDiv.innerHTML = 'hello'
//etc.
document.body.appendChild(newDiv)
将代码更改为
document.body.innerHTML="<div style=\"position:absolute; right:-10px; bottom:10px;\">response</div>\"";
document.body.innerHTML=“response\”;
删除)在结尾处,尤其是对于
元素,您不应该使用innerHTML
将元素附加到元素。更简单的方法是使用DOM方法,如createElement
、insertBefore
或appendChild
试试这个:
var div = document.createElement("div");
div.style.position = "absolute";
div.style.right = "-10px";
div.style.bottom = "10px";
div.innerHTML = "response";
var lastChild = document.body.lastChild;
document.body.insertBefore(div, lastChild.nextSibling);
尽管我认为将其附加到正文中是有意义的:
document.body.appendChild(div);
(而不是第一个示例中的最后两行)
这还取决于您何时调用此代码。当然,如果在 的中间执行,它会起作用,但是你可能要等到身体(DOM)准备好,才能将元素实际添加到身体的真正末端。通过使用类似于:
window.onload = function () {
// Your code from above
};
这将确保原始的
内容准备就绪。关于:
var div = document.createElement("div");
// it's better use a CSS here instead
div.style.position = "absolute";
div.style.right = "-10px";
div.style.bottom = "10px";
div.innerHTML = "response";
document.body.appendChild(div);
?