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文件支持 )

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

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


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:

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


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



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


Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.