當在for循環中梳理DOM調用兩個屬性(id和name)時,我遇到一些問題。javascript:結合DOM「ID」和「名稱」的錯誤
我有一個表,其中每個單元都有自己的ID,但相同的名稱屬性的HTML部分: <td id="p1" name="f" ></td> <td id="p2" name="f" ></td> ... <td id="p47" name="f" ></td>
現在我想隨意把這些細胞圖像具有以下功能:
function begintest() {
var i;
var randnum;
var randnum2;
for(i=1;i<48;i++) {document.getElementById("p" + i).name="f";
for(i=1;i<22;i++) {
randnum = Math.floor(Math.random() * 6) + 1; //picture of one sort
randnum2 = Math.floor(Math.random() * 47) + 1; //random position between 1-47
while(document.getElementById("p" + randnum2).name=="t") { //check whether position taken
randnum2 = Math.floor(Math.random() * 47) + 1; //random position between 1-47
}
document.getElementById("p" + randnum2).name = "t"; //true
document.getElementById("p" + randnum2).style.backgroundImage = "url(i" + randnum + ".png)"; //put in image first sort
}
for(i=1;i<48;i++) { //picture of second sort
if(document.getElementById("p" + i).name=="f") { //if not filled with first sort
randnum = Math.floor(Math.random() * 26) + 7; //take second sort
document.getElementById("p" + i).style.backgroundImage = "url(i" + randnum + ".png)"; //put in image second sort
}
}
}
然而,我總是得到調試信息:
TypeError: document.getElementById(...) is null for the functions where a DOM reference with 2 attributes is used, such as: if(document.getElementById("p" + i).name=="f")
怎麼能這樣呢?還有另一種處理方法嗎?
是沒有錯的代碼*本身*。如果* document.getElementById *返回'null',則表示它沒有找到該元素。嘗試訪問'null'的任何屬性都會引發錯誤。 – RobG
完全正確。非常感謝! – user2451428
何時何地調用'begintest()'?它可能在DOM準備好之前調用。 –