开发者

Problems with Random Image Script in JS

I am trying to get the following script to replace the default images by a random image every time the page refreshes. I keep getting a boxID is null error. Why is boxID null?

  <script type="text/javascript"> 
    function randomThumbs(){
    var unalafois=1;
    for (unalafois=1; unalafois<9; unalafois++){
    boxID=document.getElementById("'unalafois'")
    var duh= Math.ceil(Math.random()*8);
    boxID.src="thumbs/'+duh+'.jpg";
    }}
    </script>

Here is the HTML code:

<body onload="randomThumbs()">
<table>
    <tr>
      <td><img id="1" src="thumbs/1.jpg" /></td>
      <td><img id="2" src="thumbs/2.jpg" /></td>
      <td><img id="3" src="thumbs/3.jpg" /></td>
      <td><img id="4" src="thumbs/4.jpg" /></td>
      <td><img id="5" src="thumbs/5.jpg" /></td>
      <td><img id="6" src="thumbs/6.jpg" /></td>
      <td><img id="7" src="thumbs/7.jpg" /></td>
      <td><开发者_运维知识库img id="8" src="thumbs/8.jpg" /></td>
    </tr>
</table>
</body>

Thanks!


ID for a HTMLElement cannot start with a number. Change the ID's to something like img-n, where n is a number.

<body onload="randomThumbs()">
<table>
        <tr>
            <td><img id="img-1" src="thumbs/1.jpg" /></td>
            <td><img id="img-2" src="thumbs/2.jpg" /></td>
            <td><img id="img-3" src="thumbs/3.jpg" /></td>
            <td><img id="img-4" src="thumbs/4.jpg" /></td>
            <td><img id="img-5" src="thumbs/5.jpg" /></td>
            <td><img id="img-6" src="thumbs/6.jpg" /></td>
            <td><img id="img-7" src="thumbs/7.jpg" /></td>
            <td><img id="img-8" src="thumbs/8.jpg" /></td>
        </tr>
</table>

Then change your script to:

<script type="text/javascript"> 
    function randomThumbs(){
        var unalafois=1;
        for (unalafois=1; unalafois<9; unalafois++){
          //Use var before boxID, just a best practice
            var boxID = document.getElementById("img-" + unalafois)
            var duh= Math.ceil(Math.random()*8);
            boxID.src="thumbs/" + duh + ".jpg";
        }
    }
</script>


Remove the quotes if you want to use unalafois as a variable:

boxID=document.getElementById(unalafois)

And don't use IDs starting with numbers, it's illegal if you want to conform to HTML Specs


I figured it out! The problem was missing quotes around the 1 on line 3. Here is the final script:

<script type="text/javascript">
function randomThumbs(){
var onecell="1";
for (onecell=1; onecell<9; onecell++){
var picnum=Math.ceil(Math.random()*9);
document.getElementById("img" +onecell).setAttribute("src","thumbs/"+picnum+".jpg");
}}
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜