jQuery 单击/在两个函数之间切换 [英] jQuery click / toggle between two functions

查看:28
本文介绍了jQuery 单击/在两个函数之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,可以在单击某物时运行两个单独的操作/函数/代码块",然后在再次单击同一事物时运行完全不同的块.我把这个放在一起.我想知道是否有更有效/优雅的方式.我知道 jQuery .toggle() 但它有点糟糕.

I am looking for a way to have two separate operations / functions / "blocks of code" run when something is clicked and then a totally different block when the same thing is clicked again. I put this together. I was wondering if there was a more efficient / elegant way. I know about jQuery .toggle() but it kind of sucks.

在这里工作:http://jsfiddle.net/reggi/FcvaD/1/

var count = 0;
$("#time").click(function() {
    count++;
    //even odd click detect 
    var isEven = function(someNumber) {
        return (someNumber % 2 === 0) ? true : false;
    };
    // on odd clicks do this
    if (isEven(count) === false) {
        $(this).animate({
            width: "260px"
        }, 1500);
    }
    // on even clicks do this
    else if (isEven(count) === true) {
        $(this).animate({
            width: "30px"
        }, 1500);
    }
});

推荐答案

jQuery 有两个方法,称为 .toggle().另一个[docs]对点击事件执行您想要的操作.

jQuery has two methods called .toggle(). The other one [docs] does exactly what you want for click events.

注意:似乎至少从 jQuery 1.7 开始,这个版本的 .toggle弃用,可能正是出于这个原因,即存在两个版本.使用 .toggle 来改变元素的可见性只是一种更常见的用法.该方法在 jQuery 1.9 中删除.

Note: It seems that at least since jQuery 1.7, this version of .toggle is deprecated, probably for exactly that reason, namely that two versions exist. Using .toggle to change the visibility of elements is just a more common usage. The method was removed in jQuery 1.9.

下面是一个示例,说明如何实现与插件相同的功能(但可能会暴露与内置版本相同的问题(请参阅文档的最后一段)).

Below is an example of how one could implement the same functionality as a plugin (but probably exposes the same problems as the built-in version (see the last paragraph in the documentation)).

(function($) {
    $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

演示

(免责声明:我不是说这是最好的实现!我打赌它可以在性能方面得到改进)

然后调用它:

$('#test').clickToggle(function() {   
    $(this).animate({
        width: "260px"
    }, 1500);
},
function() {
    $(this).animate({
        width: "30px"
    }, 1500);
});

更新 2:

与此同时,我为此创建了一个合适的插件.它接受任意数量的函数并可用于任何事件.可以在 GitHub 上找到.

In the meantime, I created a proper plugin for this. It accepts an arbitrary number of functions and can be used for any event. It can be found on GitHub.

这篇关于jQuery 单击/在两个函数之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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