我對JavaScript很陌生,所以我很抱歉如果這是一個愚蠢的問題。我試圖編寫一個函數,它會在元素旁邊添加一個特定的圖像,這取決於它是真是假。當我說src.appendChild(CorrectImg)
我得到一個錯誤,它說「無法讀取空的財產的appendChild ......」如何在JavaScript中添加圖片?
function check(bool, id) {
var CorrectImg = document.createElement("CorrectImg");
CorrectImg.src = "correct.png"
var WrongImg = document.createElement("WrongImg");
WrongImg.src = "wrong.png";
if (bool) {
var src = document.getElementById(id);
src.appendChild(CorrectImg);
return;
}
var src = document.getElementById(id);
src.appendChild(WrongImg);
}
什麼是''元素? –
epascarello
以及錯誤意味着你的元素不存在。 – epascarello
應該是一個愚蠢的https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element但createElement也是錯誤的。 – epascarello