jQuery的Toggle Event函數具有been removed作爲版本1.9的一部分。等效於不推薦使用的jQuery切換事件
我使用這個功能,像這樣:
$('#example').toggle(function() {
do stuff
}, function() {
do stuff
});
什麼是重現此功能現在切換事件已經最好的方法是什麼?
jQuery的Toggle Event函數具有been removed作爲版本1.9的一部分。等效於不推薦使用的jQuery切換事件
我使用這個功能,像這樣:
$('#example').toggle(function() {
do stuff
}, function() {
do stuff
});
什麼是重現此功能現在切換事件已經最好的方法是什麼?
負載遷移並查看代碼有
見的是同一件事
Where has fn.toggle(handler(eventObject), handler(eventObject)...) gone?
我建議我的職務,他們命名它來fn.toggler而不是取消它
這裏是代碼 - 它是一個獨立的jQuery插件,可以按原樣使用。
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);
};
較短,未測試的版本:
(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);
這也非常實用。
$.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);
});
};
謝謝你。我已經使用[jQuery Migrate](https://github.com/jquery/jquery-migrate/)插件來確定此功能已被刪除(它沒有很好地記錄),但我寧願不要離開這個插件作爲解決方案。什麼會是一個很好的等價物? – AlecRust
將上面的代碼添加到腳本中。它是一個自己的插件 – mplungjan
我很驚訝沒有一個更簡潔的方式來再現此功能。雖然謝謝! – AlecRust