在javascript中添加奇数行为
在创建网页并将元素附加到网页的过程中,我遇到了javascript的一个奇怪行为,即用另一个子元素替换子元素而不是附加元素。代码如下:在javascript中添加奇数行为,javascript,appendchild,Javascript,Appendchild,在创建网页并将元素附加到网页的过程中,我遇到了javascript的一个奇怪行为,即用另一个子元素替换子元素而不是附加元素。代码如下: var window = document.createElement("div"); //the minesweeper game window window.setAttribute("class", "window"); document.body.appendChild(window); var title_bar = document.createE
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);
但与我期望看到的结果不同,具有class属性top的最新div将第一个div替换为title bar的class属性。为什么会发生这种情况?您在这里有
标题栏
,而不是顶部
(问题的最后一行):
将其替换为top
,它应该可以工作
顺便说一下,不要在浏览器中命名变量window
,因为这是全局对象引用的指定对象。调用变量game\u window
或其他类似代码
此外,您可能不关心元素的实际HTML类属性,而应该直接设置className
属性:
top.className = "top"; // instead of top.setAttribute("class", "top");
您在这里有
标题栏
,而不是顶部
(问题的最后一行):
将其替换为top
,它应该可以工作
顺便说一下,不要在浏览器中命名变量window
,因为这是全局对象引用的指定对象。调用变量game\u window
或其他类似代码
此外,您可能不关心元素的实际HTML类属性,而应该直接设置className
属性:
top.className = "top"; // instead of top.setAttribute("class", "top");