如何使用javascript检查img src是否为true

如何使用javascript检查img src是否为true,javascript,html,Javascript,Html,有5个按钮(图像)。 最初,所有这些都与图像不符。一次只能打开1个。 所以当我按下任何一个按钮,img的src就会变成on.png。然后,当我按下任何一个on或off按钮时,按下的按钮源img将变为on.png,所有其他on img也将变为off.png html代码是 <table cellspacing="0" style="padding:0%; margin:0% auto;"> <tr><td><img id="img1" src="o

有5个按钮(图像)。 最初,所有这些都与图像不符。一次只能打开1个。 所以当我按下任何一个按钮,img的src就会变成on.png。然后,当我按下任何一个on或off按钮时,按下的按钮源img将变为on.png,所有其他on 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>

45:78
45:78
45:78
45:78
45:78
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';
}
功能关闭(a)
{
var images=document.getElementsByTagName('img');
对于(var i=0;i
if()条件不起作用,请提供解决方案并解释其原因

工作。 谢谢大家!

什么是
警报(img.src)显示?如果我尝试使用stackoverflow,例如:

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

图像[0]。src==”http://stackoverflow.com/questions/18149043/on.png“
,而不是“on.png”(它是相对于当前页面的)。

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

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

您可以使用
匹配

img.src.match('on.png')
或者使用正则表达式(确保它位于字符串末尾):


您已经描述了radiogroup的行为。您不需要实现它,实现标准元素不是一个好的实践。为什么不使用这样的东西:

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


你可以自定义你想要的单选按钮,它将在没有javascript的情况下工作。

警报向你显示了什么?我建议添加一个
,并检查它,而不是
src
。警报框显示每个img的一个又一个源tag@deveshchauhan27是的,但是源文件是“one.png”还是完整路径(即http://.../one.png“)?编辑:retnuh获得完整路径../img/on.pngimg.src保存图像的完整值,因此类似于:而不是“on.png”。
<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>