2011-04-15 67 views
1

我想要获得以下脚本,以便在每次刷新页面时用随机图像替换默认图像。我不断收到一个boxID为空的错误。为什么boxID为空?随机图像脚本JS中的问题

<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> 

下面是HTML代码:

<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> 

谢谢!

回答

3

ID这是非法的对于HTMLElement不能以数字开头。 将ID更改为像img-n,其中n是一个数字。

<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> 

然后改变你的脚本:

<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> 
+0

这并没有完全解决问题,但它有很大的帮助;干杯! – Ishikawa 2011-04-15 15:22:32

1

,如果你想使用unalafois作为变量删除引号:

boxID=document.getElementById(unalafois)

,不使用的ID开始的数字,如果你想以符合HTML Specs

0

我想通了!这个问题在第3行1周围缺少引号。下面是最后一个脚本:

<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>