Javascript appendChild() 不起作用。

5
我不知道为什么以下内容无法正常工作。
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); 
};

提前感谢您的帮助。

2
“不工作”是指它没有被插入吗? - EkcenierK
1
请阅读如何提出一个好问题? - Ortomala Lokni
似乎可以工作?http://jsfiddle.net/135r1rbq/
  • 如果你想让div有内容,使用newGroup.textContent = "example";
- Leon Adler
2个回答

6
您的代码正常工作(假设您的JS位于这些元素下方)。您只是没有在元素中设置任何内容。
首先,您应该了解浏览器中的Web开发人员工具。按“F12”,在出现的窗口中的“元素”选项卡中找到您的“父”div。一旦找到“父”元素,请单击按钮。您会看到您的新div出现在“parent”下面。
但是,它没有呈现任何内容,因为它没有内容。只需执行
newGroup.textContent = "Hello, world!";

使用document.createElement创建元素后,您的子元素中将有内容。
此外,请勿将每个子元素的id设置为相同的值。HTML中的id应该是唯一的。您可能还应该考虑在代码中使用addEventListener而不是onclick。

0
你想做什么?你是想在函数外部访问parent和newGroup吗?如果是的话,你需要在函数外部声明这些变量。
var parent;
var newGroup;

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); 
};

你只是在显示一个空的 div,所以如果你想知道为什么看不到任何东西,那可能就是原因。尝试添加一个简单的字符串或 CSS 样式来查看你的新 div。这里有一个例子:http://jsfiddle.net/inspiredtolive/Lrydh3ar/2/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接