2016-11-30 6 views
1

Webページへの要素の作成と追加の手順で、javascriptの奇妙な動作に直面しました。つまり、子をappendingの代わりに別のものに置き換えています。ここでのコードは次のとおりです。appendChild javacriptの奇妙な動作

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

が、私は結果として見ることを期待するものとは異なり、トップのクラス属性を持つ最新のdivは、タイトルバーのclass属性を持つ最初のdivを置き換えます。なぜこれが起こるのですか?

答えて

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"); 
+0

あなたが正しいです。それは悪い間違いだった!ありがとうございます – Amirhossein

+0

@Amirhosseinようこそ – Paulpro