0

我创建了一个数组,用于存储一系列 .gif 图像,我只是试图通过使用 document.getElementById 来更改 .src 值来测试所有内容,但是当我更改它并加载页面时,图像仍然存在和以前一样。

    function setImage()
    {
    var images = new Array();
    images[0] = anemone.gif; 
    images[1] = ball.gif;
    images[2] = crab.gif;
    images[3] = fish2.gif;
    images[4] = gull.gif;
    images[5] = jellyfish.gif;
    images[6] = moon.gif;
    images[7] = sail.gif;
    images[8] = shell.gif;
    images[9] = snail.gif;
    images[10] = sun.gif;
    images[11] = sunnies.gif;
    images[12] = whale.gif;

    var slots = new Array();
    slots[0] = document.getElementById("slot" + 0);
    slots[1] = document.getElementById("slot" + 1);
    slots[2] = document.getElementById("slot" + 2);
    slots[0].src = "snail.gif";
    document.getElementById('slot0').src = images[0];
    alert(images.length);
    }

我不明白为什么图像不会改变,但我知道它必须非常简单。我一直在浪费时间试图改变这件事,但没有任何效果。谁能指出我的方式的错误?

4

1 回答 1

1

您的代码有几个问题:

你的文件名需要是字符串,所以它们必须被引用(你也可以简化数组的创建):

var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif'];

还要确保您的slot-elements 正确,引用所有属性,例如:

<img id="slot0" class="slot" src="crab.gif" width="120" height="80">

当您创建slots-Array 时,您可以这样做(无需连接 ID 字符串):

var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];

最后确保在文档加载/DOM 准备好时调用你的函数。如果你不想使用像 jQuery 这样的框架,你最简单的选择可能仍然是使用window.onload

window.onload = setImage; //note that the parens are missing as you want to refer to the function instead of executing it

进一步阅读 Arrays、window.onload 和 DOMReady:

于 2012-10-07T10:31:44.213 回答