简体   繁体   English

Javascript div 不起作用

[英]Javascript div doesn't work

var udiv = document.createElement('div');
var div = document.createElement("div");
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello";
div.appendChild(udiv);

I've been trying to get this to work, but when I open the page there's nothing there.我一直试图让它发挥作用,但是当我打开页面时,那里什么也没有。 I know the Javascript file works because everything else shows up, but the div doesn't.我知道 Javascript 文件有效,因为其他所有内容都显示出来,但 div 没有。 There's no error.没有错误。

您已将udiv附加到div ,但从未将div附加到 DOM。

But both are new elements, Append those elements to an already existing element or to the body ,但两者都是元素,将这些元素附加到已经存在的元素或body

.
.
.
div.appendChild(udiv);
document.body.appendChild(div)

您没有将div对象附加到 DOM

document.body.appendChild(div);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM