无法执行插入' on Node'
我正在尝试创建一个简单的HTML页面,在此之前将添加新的DIV(在专用的“工作区”中)。实现了目标,所有新的< divs>
是正确
<body>
...
<div id="workspace" >
<script type="text/javascript">
var my_div = document.getElementById("workspace");
var newDiv = null;
function addElement() {
newDiv = document.createElement("div");
newDiv.innerHTML = "<h7>Hi there and greetings!</h7>";
newDiv.style.width = "200px";
newDiv.style.height = "50px";
newDiv.style.background = "red";
my_div.appendChild(newDiv);
my_div.insertBefore(newDiv, workspace);
}
</script>
<a href="#" onclick="addElement()">ADD new greeting</a>
</div>
...
</body>
创建
的要插入新节点不是这个节点的孩子。
我在JS中是全新的,但找不到任何简单的解释。这样的代码怎么了?此错误从何而来?整个文档中不再使用JS ...
I'm trying to create a simple html page where new div will be added after previous (in dedicated "workspace"). The goal is achieved and all new <divs>
are created properly
<body>
...
<div id="workspace" >
<script type="text/javascript">
var my_div = document.getElementById("workspace");
var newDiv = null;
function addElement() {
newDiv = document.createElement("div");
newDiv.innerHTML = "<h7>Hi there and greetings!</h7>";
newDiv.style.width = "200px";
newDiv.style.height = "50px";
newDiv.style.background = "red";
my_div.appendChild(newDiv);
my_div.insertBefore(newDiv, workspace);
}
</script>
<a href="#" onclick="addElement()">ADD new greeting</a>
</div>
...
</body>
However in my console I get an error:
Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
I'm completely new in JS but I can't find any simple explanation. What is wrong with such code? Where does this error come from? No more JS is used in whole document...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为
workspace
尚未定义。您可以添加一个新变量来存储您保存的最新DIV。然后检查它是否不是零(第一次单击链接时为null。然后,您可以将
使用
将最后一个div用作第二个参数This is because
workspace
is not defined. You can add a new variable to store the latest div that you saved. Then check if it's not null (it's null when you click on the link for the first time.Then you can use
insertBefore
with the last div as the second argument