Javascript函数不适用于所有元素

时间:2014-09-22 11:57:20

标签: javascript html image src

我正在尝试编写一个在鼠标悬停时更改图像的脚本。我有6个图像,但该功能仅适用于其中一个(第一个)

<div id="picture-container">
    <img class="picture" id="360" src="360.jpg" onclick="enlarge(360);"  onmouseover="pic_info(360);"
    onmouseout="pic_ret(360);"/>
    <img class="picture" id="bmx" src="bmx.jpg" onclick="enlarge(bmx);"/>
    <img class="picture" id="buzludzha" src="buzludzha.jpg" onclick="enlarge(buzludzha);"
    onmouseover="pic_info(buzludzha);"/>
    <img class="picture" id="pirata" src="pirata.jpg" onclick="enlarge(pirata);"
    onmouseover="pic_info(pirata);"/>
    <img class="picture" id="snowboard" src="snowboard.jpg" onclick="enlarge(snowboard);"
    onmouseover="pic_info(snowboard);"/>
    <img class="picture" id="vitiskali" src="vitiskali.jpg" onclick="enlarge(vitiskali);"
    onmouseover="pic_info(vitiskali);"/>
    <img class="picture" id="ispolin" src="ispolin.jpg" onclick="enlarge(ispolin);"
    onmouseover="pic_info(ispolin);"/>

</div>

脚本:

function pic_info(id) {

if (id == "360") {
    var p = document.getElementById(id);
    p.src = "360info.jpg";
}
if (id == "buzludzha") {
    var p = document.getElementById(id);
    p.src = "buzludzhainfo.jpg";
}
if (id == "pirata") {
    var p = document.getElementById(id);
    p.src = "piratainfo.jpg";
}
if (id == "snowboard") {
    var p = document.getElementById(id);
    p.src = "snowboardinfo.jpg";
}
if (id == "vitiskali") {
    var p = document.getElementById(id);
    p.src = "vitiskaliinfo.jpg";
}
if (id == "ispolin") {
    var p = document.getElementById(id);
    p.src = "ispolininfo.jpg";
}

正如我所说,该脚本仅适用于id =“360”的图片,并且它被导入到html文档的head标签中。同样的事情发生在函数“enlarge();”中。为什么这样,我该如何解决? 提前谢谢!

1 个答案:

答案 0 :(得分:7)

只是为了划伤表面,传递一个变量而不是一个字符串:enlarge(bmx);应该是:enlarge('bmx');,依此类推其他人