is there a toggleSrc method in jQuery?

半城伤御伤魂 提交于 2019-12-25 04:26:46

问题


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:


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.



来源:https://stackoverflow.com/questions/4482351/is-there-a-togglesrc-method-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!