JAVA SCRIPT图像image.src.match问题 [英] JAVA SCRIPT image image.src.match issue

查看:100
本文介绍了JAVA SCRIPT图像image.src.match问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我尝试修改以下代码的java脚本部分为



原创代码: -



Hi,

I tried modifing the java script part of the below codes as

Original code:-

<html>
<img id="myImage" >
<script>







function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>
</html>

Modified java script :-
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src == "pic_bulbon.gif") {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}



执行此原始代码时,灯泡会同时打开和关闭。

但是当执行这个修改过的代码时,灯泡就会亮起而且它不会下车

两者都是if循环,但为什么会发生这种情况?请帮助我理解。


When this original code is executed the bulb will both on and off as many as times we click.
But when this modified code is executed the bulb will just on and it will not get off
Both are if loops but why is this happening? Kindly help me understand.

推荐答案

匹配图像src属性的更好方法是:



The better way to match image src attribute is :

function changeImage() {
    var image = document.getElementById('myImage');
    
    if (image.getAttribute('src')=="pic_bulbon.gif") {
        image.src = "pic_bulboff.gif";
    } else {
         
        image.src = "pic_bulbon.gif";
    }
}





这样做。



This works.


这篇关于JAVA SCRIPT图像image.src.match问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆