问题与随机图像脚本在JS

Problems with Random Image Script in JS

本文关键字:JS 脚本 图像 随机 问题      更新时间:2023-09-26

我试图获得以下脚本,以替换默认图像随机图像每次页面刷新。总是得到boxID为null错误。为什么boxID为空?

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

谢谢!

HTMLElement的ID不能以数字开头。将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>

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

boxID=document.getElementById(unalafois)

不要使用以数字开头的id,如果你想符合HTML规范

我明白了!问题是第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>