如何使用javascript检查img src是否正确

时间:2013-08-09 14:26:10

标签: javascript html

有5个没有。按钮(图像)。 最初都是关闭图像。一次只能打开1个。 所以,当我按下img的src变为on.png的任何按钮时。然后,当我按下任何打开或关闭按钮时,按下的按钮源img变为on.png,img上的所有其他按钮也变为off.png。

html代码是,

    <table cellspacing="0" style="padding:0%; margin:0% auto;">
<tr><td><img id="img1" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img2" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img3" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img4" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
<tr><td><img id="img5" src="off.png" height="30" width="30" onclick="off(this.id);" /></td><td>45:78</td></tr>
</table>

javascript代码是,

    function off(a)
{
    var images = document.getElementsByTagName('img');
    for(var i = 0; i < images.length; i++)
    {
        var img = images[i];
        alert(img.src);
        if(img.src == 'on.png')
        {
            img.src = 'off.png';
        }
    }
    document.getElementById(a).src='on.png';
}

if()条件不起作用,请提供解决方案并解释为什么不是

工作。 谢谢!

4 个答案:

答案 0 :(得分:8)

img.src将返回图像的完整路径(/full/path/to/on.png),而不是标记(on.png)中src属性的设置。而是使用:

if (img.getAttribute('src') === 'on.png')

答案 1 :(得分:1)

显示alert(img.src);是什么?如果我尝试使用stackoverflow:

images[0].src = 'on.png';

images[0].src == "http://stackoverflow.com/questions/18149043/on.png",而非“on.png”(相对于当前页面)。

答案 2 :(得分:0)

您可以使用match

img.src.match('on.png')

或者使用正则表达式(确保它位于字符串的末尾):

img.src.match(/on\.png$/)

答案 3 :(得分:0)

您已经描述了放射性组的行为。您不需要实现它,实现标准元素不是一个好习惯。为什么你不使用这样的东西:

<radiogroup class="custom-radio">
    <input type="radio" name="myRadio" value="1">
    <input type="radio" name="myRadio" value="2">
    <input type="radio" name="myRadio" value="3">
    <input type="radio" name="myRadio" value="4">
    <input type="radio" name="myRadio" value="5">
</radiogroup>

您可以根据需要自定义radiobuttons,并且无需javascript即可使用。