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条回答
小情绪 Triste *
2楼-- · 2020-05-19 07:59

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");
查看更多
登录 后发表回答