is there a toggleSrc method in jQuery?

2019-08-27 17:30发布

Does jQuery have something like toggleSrc :-p ??

I want to change src of an image on slideToggling of a div.is there something like that give me the chance of not writing conditional statement to check the src of image to change to another src. (I am not lazy !!!)

1条回答
混吃等死
2楼-- · 2019-08-27 18:35

There isn't a built-in method for this, but you could make a plugin for it, for example:

$.fn.toggleSrc = function(onSuffix, offSuffix) {
  return this.attr("src", function(i, src) {
    return src.indexOf(onSuffix) != -1 ? src.replace(onSuffix, offSuffix)
                                       : src.replace(offSuffix, onSuffix);
  });
};

Then you'd call it like this:

$("img").toggleSrc("_on", "_off");

...or a big safer:

$("img").toggleSrc("_on.jpg", "_off.jpg");

You can test it out here. There are (as usual) 10 other ways to do this as well, this is just one example of how to do this and save you some code repetition.

查看更多
登录 后发表回答