【问题标题】:How to check img src is true using javascript如何使用 javascript 检查 img src 是否为真
【发布时间】:2013-08-11 12:35:27
【问题描述】:

有5个没有。按钮(图像)。 最初都是关闭图像。一次只能打开 1 个。 因此,当我按下任何按钮时,img 的 src 会更改为 on.png。然后,当我按下任何这些开或关按钮时,按下的按钮源 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>

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() 条件不起作用,请提供解决方案并说明原因

工作。 谢谢!

【问题讨论】:

  • alert 告诉你什么?
  • 我建议添加一个class,并检查它而不是src
  • 警报框一一显示每个img标签的来源

标签: javascript html


【解决方案1】:

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

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

【讨论】:

【解决方案2】:

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

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

images[0].src == "http://stackoverflow.com/questions/18149043/on.png",而不是“on.png”(它与当前页面相关)。

【讨论】:

  • @deveshchauhan27 是的,但源是“one.png”还是完整路径(即“http://.../one.png”)?编辑:retnuh 明白了
  • 完整路径../img/on.png
【解决方案3】:

你可以使用match:

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

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

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

【讨论】:

    【解决方案4】:

    您已经描述了 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 的情况下工作。

    【讨论】:

      猜你喜欢
      • 2012-09-13
      • 2011-03-30
      • 2013-10-22
      • 2016-01-08
      • 1970-01-01
      • 2011-08-10
      • 2023-03-07
      • 2013-10-25
      • 2011-12-04
      相关资源
      最近更新 更多