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.
精彩评论