JavaScript变量图像不是预期的值

时间:2016-09-11 01:47:14

标签: javascript jquery html dom

我是HTML和JavaScript的完全初学者。我遇到了问题。我有一个按钮,在onclick下,我有:

onclick="document.getElementById('slideCurrent').src=images[1]"

在JavaScript部分,我有:

var images = [
    "PATH BLABLABLA_1",
    "PATH BLABLABLA_2",
    "PATH BLABLABLA_3"
];

出于某种原因,它不会显示图像。但是,如果我直接将路径放在那里,它将正常工作。

我想要的是根据数组索引显示适当的图像。出于某种原因,控制台告诉我路径不正确:
Failed to load resource: net::ERR_FILE_NOT_FOUND

以下是更完整的代码:

    <img id="slideCurrent" 
         src="file:///C:/Users/philip/Desktop/htmlCSA_files/CSA_InfoGuide_TUTORIALSLIDE1.png"
         width="500"
         height="333"/>

    <input type="image"
           id="arrowCircularRight"
           src="file:///C:/Users/philip/Desktop/htmlCSA_files/arrowCircular_right.png"
           onclick="document.getElementById('slideCurrent').src=images[1]"
           width="50" 
           height="50"/>
    <script>
    var images = [
        "file:///C:/Users/philip/Desktop/htmlCSA_files/CSA_InfoGuide_TUTORIALSLIDE1.png",
        "file:///C:/Users/philip/Desktop/htmlCSA_files/CSA_InfoGuide_TUTORIALSLIDE2.png",
        "file:///C:/Users/philip/Desktop/htmlCSA_files/CSA_InfoGuide_TUTORIALSLIDE3.png",
        "file:///C:/Users/philip/Desktop/htmlCSA_files/CSA_InfoGuide_TUTORIALSLIDE4.png",
        "file:///C:/Users/philip/Desktop/htmlCSA_files/CSA_InfoGuide_TUTORIALSLIDE5.png"
    ];

</script>

1 个答案:

答案 0 :(得分:1)

问题是您选择变量名称。变量imagesdocument.images冲突。如果您使用其他变量名称,它将起作用。

以下是代码段中的代码(稍加修改)。为了进行测试,我已将图像URL更改为在Stack Overflow上有效的URL,调整了<img>的大小,并添加了一行来说明要单击的图像。我将变量名称从images更改为myImages

<img id="slideCurrent" src="http://i.stack.imgur.com/jy5g5.png"/>

<p>Click the image below to change the one above this line (only changes once)</p>

<input type="image"
    id="arrowCircularRight"
    src="http://i.stack.imgur.com/wRMuO.png"
    onclick="document.getElementById('slideCurrent').src=myImages[1];"
    width="50" 
    height="50"/>

<script>
    var myImages = [
        "http://i.stack.imgur.com/jy5g5.png",
        "http://i.stack.imgur.com/S33VZ.png"
    ];
</script>