使用javascript创建div onclick
我使用纯JavaScript在用户单击另一个div时创建一个新的div元素。未报告错误,但未创建div。请帮忙。非常感谢你 基本上,这就是我现在拥有的:使用javascript创建div onclick,javascript,html,Javascript,Html,我使用纯JavaScript在用户单击另一个div时创建一个新的div元素。未报告错误,但未创建div。请帮忙。非常感谢你 基本上,这就是我现在拥有的: document.getElementByID("text").onclick = function () { var ok = true; }; if (ok === true) { var div = document.createElement('div'); div.style.backgroundColor
document.getElementByID("text").onclick = function () {
var ok = true;
};
if (ok === true) {
var div = document.createElement('div');
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "50px";
div.style.top = "50px";
}
<div id="text" style="width:20%;height:30px;background-color:blue;"></div>
ok
变量是onclick
函数的本地变量。只需将var
声明移到onclick
之外:
var ok = false;
document.getElementById("text").onclick = function () {
ok = true;
};
...
同样正如j08691对这个答案的评论:它是
getElementById
,而不是getElementById
(ID中小写的d)。使用appendChild将它添加到DOM中的某个地方。例如:
document.getElementById("text").onclick = function () {
var div = document.createElement('div');
div.style.height = "200px";
div.style.backgroundColor = "black";
document.body.appendChild(div);
}
您需要在回调函数中添加创建div的逻辑
document.getElementById("text").onclick = function () {
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.style.backgroundColor = "black";
div.style.position = "absolute";
div.style.left = "50px";
div.style.top = "50px";
document.getElementsByTagName('body')[0].appendChild(div); // add it to any dom element you want
}
};
看看这个例子
var myElement=getElementById("someID");------this will create a handle on a DOM Element
var myNewElement=docment.createElement("div");----Create a div somewhere on the cloud
myElement.appenchild(myNewElement);-----attach/append that newly created element to the
handle
我建议您使用addEventListener方法将事件添加到DOM元素。此外,不要通过JavaScript应用CSS样式;更好的解决方案是添加类名并为其创建CSS规则
var addRect = function(){
var ok = true;
if (ok === true) {
var div = document.createElement('div');
div.className = 'new-rect';
document.getElementsByTagName('body')[0].appendChild(div);
}
}
document.getElementById("text").addEventListener('click', addRect);
您刚刚通过document.createElement('div')在云上的某个位置创建了一个div元素,但从未将其附加到需要该div元素的元素上。 因此,必须将其附加为某个父元素的子元素。 让我们来看看这个例子
var myElement=getElementById("someID");------this will create a handle on a DOM Element
var myNewElement=docment.createElement("div");----Create a div somewhere on the cloud
myElement.appenchild(myNewElement);-----attach/append that newly created element to the
handle
我希望这有帮助
另外,为了避免歧义,在创建变量时,我建议不要使用“div”这个名称。在Chrome中打开此小提琴,然后按ctrl+shift+I。有一个错误:Uncaught TypeError:Object#没有“getElementByID”方法。另外,创建元素还不够,您必须使用insertBefore或类似的函数将其插入DOM中,然后才能创建div(前提是修复
ok
的范围和getElementByID
中的键入)但是你从来没有把它附加到任何东西上。@NathanielJohnson这个错误是什么意思?你有一个打字错误(ID应该是ID)它不应该是document.body
?“按原样编写的代码对我不起作用。@Daniellisk是的,我没有注意到这一点;看看更新后的答案,我知道你做了什么,但你如何使其位置绝对化?你没有具体说明,但你可以在波利亚尼的答案中看到如何做到这一点。