Switching an image using jQuery

后端 未结 7 1848
醉酒成梦
醉酒成梦 2021-02-01 23:29

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

var image = $(obj).children(\"img\");
if ($(image).attr(\"src\") == \"Images/TreeColl         


        
相关标签:
7条回答
  • 2021-02-02 00:13

    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?

    0 讨论(0)
  • 2021-02-02 00:14

    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"); }
    );
    
    0 讨论(0)
  • 2021-02-02 00:15

    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.

    0 讨论(0)
  • 2021-02-02 00:17

    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");}
    );
    
    0 讨论(0)
  • 2021-02-02 00:19

    Your image object would already be a jQUery instance so there is no need for you to pass it through $(...) again.

    A good practice is to prepend variables that are jquery instances with $ and use them directly thereafter.

    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");
    
    0 讨论(0)
  • 2021-02-02 00:30

    Possible alternatives:

    • Use toggleClass and put the images in stylesheet as background images.
    • Use 2 images and toggle them.
    0 讨论(0)
提交回复
热议问题