开发者

Checking image name using javascript

开发者 https://www.devze.com 2023-02-23 08:46 出处:网络
I\'m changing the img src on click using javascript. I\'m trying to determine whether to switch on or off.

I'm changing the img src on click using javascript.

I'm trying to determine whether to switch on or off.

I'm testing the following:

var img_el = documen开发者_高级运维t.getElementById("on_off_img");
if ( img_el.src == 'img/on.png' ) {

  img_el.src = 'img/off.png'
} else {

  img_el.src = 'img/on.png'
}

My problem is that i never get a match - it looks like img_el.src returns the full URL... Is there a function to just test the actual filename instead of the full string to the file?

Or is there a better way to manage the click?


use indexOf() instead of comparing the src

e.g

var img_el = document.getElementById("on_off_img");
if ( img_el.src.indexOf('on.png') > -1) {
  img_el.src = 'img/off.png'
} else {

  img_el.src = 'img/on.png'
}


Yuo can always use indexOf:

if(img_el.src.indexOf('img/on.png') > -1){
  img_el.src = 'img/off.png'
}else{
  img_el.src = 'img/on.png'
}


To shorten this even more, you can use a ternary operator:

var img_el = document.getElementById("on_off_img"),
    isOn   = img_el.src.indexOf('on.png')>-1;
img_el.src = isOn ? 'img/off.png' : 'img/on.png';


You can use match statement aswell.

var img_el = document.getElementById("on_off_img");
if ( img_el.src.match("on.png")) 
{
  img_el.src = 'img/off.png'
} else 
{
  img_el.src = 'img/on.png'
}


Try using JQuery:

$("#on_off_img").click(function(){
    if($(this)[0].nameProp == "on.png")
        $(this).attr("src","img/off.png");
    else
        $(this).attr("src","img/on.png");         
});
0

精彩评论

暂无评论...
验证码 换一张
取 消