jQuery:无限循环两个或者多个事件 click / toggle between two functions

插件:

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

 

用法:( 需要jquery文件支持 )

<script type="text/javascript" src="https://code.jquery.com/jquery-1.5.js"></script>
<script>
$(function()
{
    $('div').clickToggle(function() {
        alert('First handler: ' + $(this).text());
    }, function() {
        alert('Second handler: ' + $(this).text());
    });
})
</script>

<div>1. div (click me)</div><br />
<div>2. div (click me)</div>

 

DEMO:http://jsfiddle.net/npwAz/1/

 

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.

 

Update 2: 多事件循环,接受jquery 1.11版本

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.

 

可以接受两个或两个以上函数循环执行,方法如下:

The function funcToggle provides the same interface as bind but accepts multiple event handlers:

funcToggle(eventType, [eventData], handler(eventObject),  [handler(eventObject), ...])

This changes the text color on each consecutive click, from to original color to red, to green, to black, to red again and so forth:

element.funcToggle('click', function() {
    $(this).css('color', 'red');
}, function() {
    $(this).css('color', 'green');
}, function() {
    $(this).css('color', 'black');
});

 

Bind handlers for multiple events:

element.funcToggle({
    'click': [function() {
            $(this).css('color', 'red');
        }, function() {
            $(this).css('color', 'green');
        }, function() {
            $(this).css('color', 'black');
        }],
    'mouseover': [function() {
            $(this).css('background-color', 'red');
        }, function() {
             $(this).css('background-color', 'white');
        }]
});

 

下载:jQuery-Function-Toggle-Plugin-master

DEMO: http://sources.ikeepstudying.com/jquery-functions-toggle/

 

更多内容参考:http://stackoverflow.com/questions/4911577/jquery-click-toggle-between-two-functions

本文转自:jQuery:无限循环两个或者多个事件 click / toggle between two functions

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值