簡體   English   中英

在javascript中appendChild奇怪的行為

[英]appendChild odd behavior in javascript

在創建和添加元素到網頁的過程中,我遇到了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屬性的最新div用title-bar的class屬性替換第一個div。 為什么會這樣?

你有title_bar而不是top (你問題的第二行):

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

top替換它,它應該工作。

順便說一下,不要在瀏覽器中命名變量window ,因為這是全局對象引用的分配。 game_window調用你的變量game_window或其他類似的東西。

您也可能不關心元素的實際HTML類屬性,而應直接設置className屬性:

top.className = "top"; // instead of top.setAttribute("class", "top");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM