我還是新的JavaScript,所以我們期待看到很多不好的編程習慣......用Javascript添加HTML元素,看不到元素?
function addButton(name, state) {
numButtons += 1;
if (name === '') {
var i = 0;
while(buttonStates.hasOwnProperty("button" + i) === true) i++;
name = "button" + i;
}
document.getElementById("buttonTable").innerHTML +=
"<tr>\
<td>\
<p id=\"buttonName" + numButtons + "\" class=\"buttonName\">" + name + "</p>\
</td><td>\
<button id=\"" + name + "\" onclick=\"setButton(this, 'toggle')\" class=\"button\">OFF</button>\
</td>\
</tr>";
//===IMPORTANT AREA 1==========================================================//
//setTimeout(function(){setButton(document.getElementById(name), state)}, 0); //works
setButton(document.getElementById(name), state); //doesn't work, no change
//=============================================================================//
}
function setButton(elem, state) {
//this is where the button's colors are set to light colors
//notice how I am using elem.style.backgroundColor
if(String(state) === 'toggle') state = !buttonStates[elem.id];
if (String(state) === 'true') {
buttonStates[elem.id] = true;
elem.style.backgroundColor = "rgb(112,192,112)";
elem.textContent = 'ON';
} else {
buttonStates[elem.id] = false;
elem.style.backgroundColor = "rgb(255,128,128)";
elem.textContent = 'OFF';
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("demo").innerHTML = this.responseText;
//===IMPORTANT AREA 2==========================================================//
if (buttonStates[elem.id] === true) {
elem.style.backgroundColor = 'green'; //doesn't work, no change. Notice how I am, again, using elem.style.backgroundColor
//document.getElementById(elem.id).style.backgroundColor = 'green'; //works
} else {
elem.style.backgroundColor = 'red';
}
//=============================================================================//
} else {
document.getElementById("demo").innerHTML = "readyState: " + this.readyState + "<br>status: " + this.status;
}
};
xhttp.open("POST", "/buttonToggle", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(elem.id + "=" + buttonStates[elem.id]);
}
所以基本上我在Add按鈕()添加一個HTML按鈕,它調用setButton()並將新元素傳遞給該函數。在setButton()中,它首先將元素的顏色設置爲淺綠色或淡紅色,表示服務器尚未更新按鈕的狀態。這部分工作正常,按鈕的顏色會改變。但是,在服務器請求的回調函數中,按鈕拒絕按照之前使用的方法改變顏色。我已經找到了解決方法(通過使用setTimeout()的時間爲0毫秒,或通過使用傳遞的元素再次從文檔中獲取元素),但我想知道爲什麼會發生這種情況。這似乎只是回調函數中的一個問題。我已驗證回調函數執行並且執行用於更改顏色的代碼。作爲一個方面說明,如果我有多個按鈕,最後一個按鈕可以正常工作,並且所有那些按鈕不起作用,它們的顏色仍然是淺綠色或淺紅色。 Notice buttons 0-5 are all a light color, yet button6 is solid, WHY?!?
這不就是我在這裏做的嗎? \ –