开发者

document.getElementById("items_" + i) is null

I have the following code:

<script type="text/javascript">
for(var i=1; i<=3; i++) {
    document.getElementById("items_"+i).checked=true;
}
</script&开发者_如何转开发gt;                   

With the following HTML

<input type="checkbox" id="items_1" name="myitems" value="1" />
<input type="checkbox" id="items_2" name="myitems" value="2" />
<input type="checkbox" id="items_3" name="myitems" value="3" />

I get an error saying:

document.getElementById("items_" + i) is null.

How do I fix this?


The first index in your for loop will be zero.

Do you have an element with the id items_0 ?

That's likely what's causing your problem. Set the initial value of i to 1

Secondly, you want to make sure that your Javascript code executes after the DOM has loaded.

I recomend you look into using jQuery as this makes it so much simpler to do these kinds of things.


Well your code looks like it's first iteration is pointed to i = 0 so it's trying to find an input tag with the id of 'items_0'.

Here is a JSBin that shows the code working correctly:

http://jsbin.com/amonel/edit


var VanillaRunOnDomReady = function() {
    // code to execute after DOM has loaded  
    for (var i = 1; i <= 3; i++) {        
        document.getElementById("items_" + i).checked = true;
    }  
}

var alreadyrunflag = 0;
if (document.addEventListener) {    
    document.addEventListener("DOMContentLoaded", function(){
        alreadyrunflag=1;
        VanillaRunOnDomReady();
    }, false);
}
else if (document.all && !window.opera) {
    document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');

    var contentloadtag = document.getElementById("contentloadtag");

    contentloadtag.onreadystatechange=function(){
        if (this.readyState=="complete"){
            alreadyrunflag=1;
            VanillaRunOnDomReady();
        }
    }
}

window.onload = function(){
  setTimeout("if (!alreadyrunflag){VanillaRunOnDomReady}", 0);
}


I ended up using:

$('#items_'+i).attr("checked", true);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜