嘗試編輯狀態DIV時出現奇怪的錯誤。TypeError:無法設置未定義的屬性'backgroundColor'
styleBox()函數應該通過更改顏色和backgroundColor來編輯狀態DIV。但是我每次運行函數時我得到這個錯誤:
TypeError: Cannot set property 'backgroundColor' of undefined
它沒有意義的,我是因爲當我看到如果我選擇正確的股利,我沒有得到一個未定義的錯誤:
document.getElementById('status');
>> <div id="status" style></div>
我認爲它與狀態DIV中的「樣式」有關,但不知道如何繼續。我看着here,但這與選擇類而不是ID有關。
我的代碼如下:
<!DOCTYPE html>
<html>
<head>
<title>
Day 11 - Functions Visuals
</title>
<style>
#box {
width:200px;
height:200px;
background-color:black;
}
</style>
</head>
<body>
<div id="group">
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
<div id="status" style=""></div> << -- This is what is tripping me up
</div>
<div id="box"></div>
<script type="text/javascript">
// Create variables for each id
blueButton = document.getElementById('blue');
redButton = document.getElementById('red');
greenButton = document.getElementById('green');
status = document.getElementById('status');
box = document.getElementById('box');
function styleBox() {
box.style.width = "50px";
box.style.height = "50px";
status.innerHTML = "The box is changed";
status.style.backgroundColor = "#000000";
status.style.color = "#FFF";
};
</script>
</body>
</html>
被稱爲狀態*的全局變量*可能與https://developer.mozilla.org/en-US/docs/Web/API/Window/status –
衝突謝謝@JaromandaX你是正確的。我不知道保留名稱列表https://www.w3schools.com/js/js_reserved.asp – Chef1075