开发者

is there a toggleSrc method in jQuery?

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 !!!)


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜