2013-01-15 10 views

risposta

12

Caricare il migrare e vedere il codice ci

Vedere il mio post sulla stessa cosa

Where has fn.toggle(handler(eventObject), handler(eventObject)...) gone?

Ho suggerito che rinominarlo a fn.toggler invece di rimuoverlo

Ecco il codice: è un plugin jQuery autonomo e può essere utilizzato così com'è.

jQuery.fn.toggle = function(fn, fn2) { 
    // Don't mess with animation or css toggles 
    if (!jQuery.isFunction(fn) || !jQuery.isFunction(fn2)) { 
    return oldToggle.apply(this, arguments); 
    } 
    // migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated"); 
    // Save reference to arguments for access in closure 
    var args = arguments, 
    guid = fn.guid || jQuery.guid++, 
    i = 0, 
    toggler = function(event) { 
    // Figure out which function to execute 
    var lastToggle = (jQuery._data(this, "lastToggle" + fn.guid) || 0) % i; 
    jQuery._data(this, "lastToggle" + fn.guid, lastToggle + 1); 
    // Make sure that clicks stop 
    event.preventDefault(); 
    // and execute the function 
    return args[ lastToggle ].apply(this, arguments) || false; 
    }; 
    // link all the functions, so any of them can unbind this click handler 
    toggler.guid = guid; 
    while (i < args.length) { 
    args[ i++ ].guid = guid; 
    } 
    return this.click(toggler); 
}; 

Shorter, versione non testato:

(function($){ 
    $.fn.toggler = function(fn, fn2) { 
    var args = arguments,guid = fn.guid || $.guid++,i=0, 
    toggler = function(event) { 
     var lastToggle = ($._data(this, "lastToggle" + fn.guid) || 0) % i; 
     $._data(this, "lastToggle" + fn.guid, lastToggle + 1); 
     event.preventDefault(); 
     return args[ lastToggle ].apply(this, arguments) || false; 
    }; 
    toggler.guid = guid; 
    while (i < args.length) { 
     args[ i++ ].guid = guid; 
    } 
    return this.click(toggler); 
    }; 
})(jQuery); 
+0

Grazie per quello. Ho già utilizzato il plugin [jQuery Migrate] (https://github.com/jquery/jquery-migrate/) per determinare che questa funzione è stata rimossa (non è stata documentata molto bene), ma preferirei non lasciare questo plug-in come soluzione. Quale sarebbe un buon equivalente? – AlecRust

+0

Aggiungi il codice sopra ai tuoi script. è un plugin a sé stante – mplungjan

+2

Sono sorpreso che non c'è un modo più conciso di riprodurre questa funzionalità. Grazie comunque! – AlecRust

8

Questo funziona bene anche.

$.fn.toggleClick = function(){ 

    var functions = arguments ; 

    return this.click(function(){ 
      var iteration = $(this).data('iteration') || 0; 
      functions[iteration].apply(this, arguments); 
      iteration = (iteration + 1) % functions.length ; 
      $(this).data('iteration', iteration); 
    }); 
};