如何解决高(新)版本的jquery不支持toggle()

时间:2016-09-07
jquery中的toggle()方法用于绑定两个或多个事件处理器函数,以响应被选元素的轮流的 click 事件,也就说,toggle()方法可以实现切换效果,但是在新版本的jquery中并不支持toggle()方法,那么如何使高版本的jquery支持toggle()呢?

在js代码中引入以下代码,让高版本的jquery兼容toggle事件。代码如下:

/**
 * Replacement for toggle
 */
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 );
	}
	// 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 );
};