jQuery中是否有toggleSrc方法? [英] is there a toggleSrc method in jQuery?

查看:90
本文介绍了jQuery中是否有toggleSrc方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery是否有类似toggleSrc的内容:-p?

Does jQuery have something like toggleSrc :-p ??

我想在slideToggling上更改图像的src.是否有类似的东西让我有机会不编写条件语句来检查图像的src更改为另一个src. (我不懒!!!)

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);
  });
};

然后您将这样称呼它:

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

...或更安全:

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

您可以在此处进行测试.同样,还有10种 other 方式可以做到这一点,这只是如何做到这一点并为您节省一些代码重复的一个示例.

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.

这篇关于jQuery中是否有toggleSrc方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆