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

相关推荐