在javascript中appendChild奇怪的行为

时间:2016-11-30 04:51:18

标签: javascript appendchild

在向网页创建和附加元素的过程中,我遇到了javascript的奇怪行为,即用另一个替换孩子而不是追加。这是代码:

var window = document.createElement("div"); //the minesweeper game window
window.setAttribute("class", "window");
document.body.appendChild(window);

var title_bar = document.createElement("div");//the title bar of the window
title_bar.setAttribute("class", "title-bar");
window.appendChild(title_bar);

var game_title = document.createElement("span");//the title of the game
game_title.setAttribute("id", "game-title");
game_title.innerHTML = "Minesweeper Online - Beginner!";
title_bar.appendChild(game_title);

var right_corner_div = document.createElement("div");// right corner buttons
title_bar.appendChild(right_corner_div);

var btn_minimize = document.createElement("span");//the minimize button
btn_minimize.setAttribute("class", "btn");
btn_minimize.setAttribute("id", "btn-minimize");
btn_minimize.innerHTML = "-";
right_corner_div.appendChild(btn_minimize);

var btn_close = document.createElement("span");//the close button
btn_close.setAttribute("class", "btn");
btn_close.setAttribute("id", "btn-close");
btn_close.style.marginLeft = "3px";
btn_close.innerHTML = "×";
right_corner_div.appendChild(btn_close);

var top = document.createElement("div");//top of window div, underneath the title bar
title_bar.setAttribute("class", "top");
window.appendChild(top);

但与我期望看到的结果不同,具有top属性top的最新div用title-bar的class属性替换第一个div。为什么会这样?

1 个答案:

答案 0 :(得分:0)

您这里有title_bar而不是top(问题的第二行):

var top = document.createElement("div");
*title_bar*.setAttribute("class", "top");
window.appendChild(top);

将其替换为top,它应该有效。

顺便说一句,不要在浏览器中命名变量window,因为这是全局对象引用的分配。相反,请调用变量game_window或其他内容。

此外,您可能不关心元素的实际HTML类属性,而应直接设置className属性:

top.className = "top"; // instead of top.setAttribute("class", "top");
相关问题