2017-07-06 79 views
1

我想僅使用JavaScript創建邊欄,但無法將關閉按鈕添加到div。 我試過這個:JS - 如何使用appendChid將按鈕添加到div中

var sideb = document.createElement("Div"); 
    sideb.style.height = "100%"; 
    sideb.style.width = "0px"; 
    sideb.style.backgroundColor = "rgb(30,30,30)"; 
    sideb.style.top = "0px"; 
    sideb.style.right = "0px"; 
    sideb.style.margin = "0px"; 
    sideb.style.padding = "0px"; 
    sideb.style.position = "fixed" 

    document.body.appendChild(sideb); 

var close = document.createElement("Button"); 
    close.innerText = "close"; 
    close.onclick = close; 

    document.body.sideb.appendChild(close) 

但它不工作。

回答

4
document.body.sideb.appendChild(close) 

body沒有所謂的屬性/鍵sideb

你只需要

sideb.appendChild(close) 
0

document.body.sideb這種形式意味着你調用一個屬性調用sideb,有在你的身體對象中沒有sideb,所以只需使用sideb.appendChild()

var sideb = document.createElement("Div"); 
sideb.style.height = "100%"; 
sideb.style.width = "0px"; 
sideb.style.backgroundColor = "rgb(30,30,30)";     sideb.style.top = "0px"; 
sideb.style.right = "0px"; 
sideb.style.margin = "0px"; 
sideb.style.padding = "0px"; 
sideb.style.position = "fixed" 
document.getElementByTagName('body')[0].appendChild(sideb); 
var close = document.createElement("Button"); 
close.innerText = "close"; 
close.onclick = close; 
sideb.appendChild(close) 
+0

呵呵呵你是對的 – Osama

+0

昆汀評論解碼。請寫幾行關於你的答案,而不是僅僅給出工作代碼。 –

1

您的代碼中有幾個錯誤。你做了一個叫做close的函數嗎?我問這是因爲您將close分配給按鈕的onclick處理程序,但是在您將close定義爲本地作用域中的按鈕元素之後。如果不是,你必須寫一個函數來實際「關閉」div。另外,另一位人士指出,sideb不是document.body的財產。您可以撥打sidebappendChild方法添加按鈕。

var sideb = document.createElement("Div"); 
sideb.style.height = "100%"; 
sideb.style.width = "0px"; 
sideb.style.backgroundColor = "rgb(30,30,30)"; 
sideb.style.top = "0px"; 
sideb.style.right = "0px"; 
sideb.style.margin = "0px"; 
sideb.style.padding = "0px"; 
sideb.style.position = "fixed"; 

document.body.appendChild(sideb); 

var close = document.createElement("Button"); 
close.innerText = "close"; 
close.onclick = function() { 
    sideB.parentNode.removeChild(sideB); 
}; 

sideb.appendChild(close); 

另外,如果你想刪除一些重複代碼,你可以使用Object.assign刪除對sideb.style所有的額外引用。

Object.assign(sideb.style, { 
    height: "100%", 
    width: "0px", 
    backgroundColor: "rgb(30,30,30)", 
    top: "0px", 
    right: "0px", 
    margin: "0px", 
    padding: "0px", 
    position: "fixed" 
});