等效的不推荐使用的jQuery Toggle事件 [英] Equivalent of deprecated jQuery Toggle Event

查看:71
本文介绍了等效的不推荐使用的jQuery Toggle事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jQuery的切换事件函数具有

jQuery's Toggle Event function has been removed as part of version 1.9.

我正在像这样使用此功能:

I was using this function like so:

$('#example').toggle(function() {
    do stuff
}, function() {
    do stuff
});

现在Toggle Event消失了,重现此功能的最佳方法是什么?

What would be the best way to reproduce this functionality now Toggle Event has gone?

推荐答案

加载MIGRATE并在其中查看代码

Load the MIGRATE and see the code there

查看我关于同一件事的帖子

See my post about the same thing

哪里有fn.toggle(handler(eventObject),handler(eventObject) ...)走了?

我建议他们将其重命名为 fn.toggler ,而不是将其删除

I have suggested they rename it to fn.toggler instead of removing it

这是代码-这是一个自包含的jQuery插件,可以按原样使用.

Here is the code - it is a self-contained jQuery plugin and can be used as is.

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, non-tested version:

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

这篇关于等效的不推荐使用的jQuery Toggle事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆