Switching an image using jQuery

2020-05-19 07:09发布

Is there a better, more jQuery-ish way of handling this image substitution?

var image = $(obj).children("img");
if ($(image).attr("src") == "Images/TreeCollapse.gif")
   $(image).attr("src", "Images/TreeExpand.gif");
else
   $(image).attr("src", "Images/TreeCollapse.gif");

标签: jquery image
7条回答
Fickle 薄情
2楼-- · 2020-05-19 07:40

You could do something like this

e.g

$(function()
    {
       $(obj)
       .children("img")
       .attr('src', swapImage );    
    });

function swapImage(){
    return ( 
              $(this).attr('src') == "Images/TreeCollapse.gif" ?
                                     "Images/TreeExpand.gif" :
                                     "Images/TreeCollapse.gif");
}

N.B in your question you do $(image) multiple times. Its better to cache the lookup in a var e.g var $image=$(obj).children("img"); then use the $image from there on in.

查看更多
Animai°情兽
3楼-- · 2020-05-19 07:40

Possible alternatives:

  • Use toggleClass and put the images in stylesheet as background images.
  • Use 2 images and toggle them.
查看更多
男人必须洒脱
4楼-- · 2020-05-19 07:47

Not really.

I know... extremely helpful answer. What you are doing is pretty succinct and I'm not so sure there would be anything to make it more "jQueryish" as you ask.

now depending on how you are iterating through this if you are doing it to multiple image instances, that is where there might be some jQuery optimizations.

查看更多
等我变得足够好
5楼-- · 2020-05-19 07:47

Wow. Answers come flying in, don't they? All of the above would work, but you could try this for a one-liner (it's untested)...

image.setAttribute("src", "Images/Tree" + ((image.getAttribute("src").indexOf("Collapse")>0) ? "Expand" : "Collapse") + ".gif");

Update: I've just tested this and it works, so would the person who voted it down care to explain why they did that?

查看更多
神经病院院长
6楼-- · 2020-05-19 07:49

More jQueryish? Maybe! Clearer? I'm not sure!

var image = $(obj).children("img");
$(image).toggle(
  function () { $(image).attr("src", "Images/TreeExpand.gif");},
  function () { $(image).attr("src", "Images/TreeCollapse.gif");}
);
查看更多
▲ chillily
7楼-- · 2020-05-19 07:58

Why set a variable when it isn't needed?

$(obj).children("img").toggle(
  function(){ $(this).attr("src", "Images/TreeExpand.gif"); },
  function(){ $(this).attr("src", "Images/TreeCollapse.gif"); }
);
查看更多
登录 后发表回答