我不知道为什么以下内容不起作用。
HTML:
...
<div class="col2">
<h2>Your Groups</h2>
<input type="submit" id="addnew" class="btn btn-primary" value="Create New Group"/>
<div id="parent">
<!--new div here-->
</div>
</div>
...
Javascript:
document.getElementById('addnew').onclick = function(){
var parent = document.getElementById('parent');
var newGroup = document.createElement("div");
newGroup.setAttribute("id", "newGroup");
newGroup.setAttribute("class", "inner");
parent.appendChild(newGroup);
};
预先感谢您的帮助。
最佳答案
您的代码正在运行(假设您的 JS 位于这些元素下方)。您只是没有在元素中设置任何内容。
首先,您应该了解浏览器中的网络开发人员工具。点击“F12”,然后在出现的窗口的“元素”选项卡中找到“父”div。找到“父”元素后,单击按钮。您会看到新的 div 出现在“parent”下。
但是,它没有呈现任何内容,因为它没有内容。简单的做
newGroup.textContent = "Hello, world!";
在使用 document.createElement 创建元素后,您现在将在您的 child 中拥有内容。
此外,不要将每个 child 的 id 设置为相同的值。 HTML 中的 ID 是唯一的。您也许还应该考虑使用 addEventListener而不是在您的代码中使用 onclick。
关于Javascript appendChild() 不工作。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33838339/