我需要添加一个带有一些元素的标签,但innerHTML插入在appendChild之前。 我的Js函数:
function addFields(){
var isbn_container = document.getElementById("isbn_container");
isbn_container.innerHTML += "<div>";
var div = document.createElement("div");
var input = document.createElement("input");
input.type = "text";
input.name = "new-isbn-10[]";
isbn_container.appendChild(input);
var input2 = document.createElement("input");
input2.type = "text";
input2.name = "new-isbn-13[]";
isbn_container.appendChild(input2);
isbn_container.innerHTML += "<span onclick='deleted(this);'> delete</span>";
isbn_container.appendChild(document.createElement("br"));
isbn_container.appendChild(document.createElement("br"));
isbn_container.after.innerHTML += "</div>";
}
结果:
<div></div>
<input type="text" name="new-isbn-10[]">
<input type="text" name="new-isbn-13[]">
<span onclick="deleted(this);"> delete</span>
<br><br>
但我想要:
<div>
<input type="text" name="new-isbn-10[]">
<input type="text" name="new-isbn-13[]">
<span onclick="deleted(this);"> delete</span>
<br><br>
</div>
请帮助我。
最佳答案
在您的代码中:
function addFields(){
var isbn_container = document.getElementById("isbn_container");
isbn_container.innerHTML += "<div>";
不要这样做,这是无效的标记,并且完全没有必要给出以下行:
var div = document.createElement("div");
var input = document.createElement("input");
input.type = "text";
input.name = "new-isbn-10[]";
isbn_container.appendChild(input);
您希望将其放在 div 中,所以不要这样做,将其添加到 div 中:
div.appendChild(input);
这里也一样:
var input2 = document.createElement("input");
input2.type = "text";
input2.name = "new-isbn-13[]";
isbn_container.appendChild(input2);
替换为:
div.appendChild(input2);
再次强调,向 isbn_container 添加内容不会将其放入 div 中,所以不要这样做:
isbn_container.innerHTML += "<span onclick='deleted(this);'> delete</span>";
isbn_container.appendChild(document.createElement("br"));
isbn_container.appendChild(document.createElement("br"));
这样做:
div.innerHTML += "<span onclick='deleted(this);'> delete</span>";
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
现在所有内容都在 div 中,因此您现在可以将 div 添加到文档中:
isbn_container.appendChild(div);
}
关于javascript - JS - 在 <div> 标签上插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27894992/