jquery toggle方法

.toggle(function, function, … )

link .toggle(function, function, ... ) removed

This is the "click an element to run the specified functions" signature of .toggle(). It should not be confused with the "change the visibility of an element" of .toggle() which is not deprecated. The former is being removed to reduce confusion and improve the potential for modularity in the library. The jQuery Migrate plugin can be used to restore the functionality.

需要注意的是该.toggle()是“绑定两个或多个处理程序,在点击时循环执行”;另一个.toggle()仍然存在,它是“控制相应组件的显示和隐藏”;中文晦涩,官方对此二方法的说明如下:

Categories: Deprecated > Deprecated 1.8 | Events > Mouse Events

.toggle(handler(eventObject), handler(eventObject) [,handler(eventObject)])

Returns:jQuery

version deprecated: 1.8, removed: 1.9

Description:Bind two or more handlers to the matched elements, to be executed on alternate clicks.

Categories: Effects > Basics

.toggle( [duration ] [, complete ] )

Returns:jQuery

Description:Display or hide the matched elements.

这个变化值得注意。对于删除的这个“.toggle()”方法,官方没有给出升级措施,但我发现一个方法名和描述都比较相似的方法“.trigger()”,不知道可不可以替代。

我用2.0.0版本执行下面版本:

$(function () {

  $("h5").toggle(function () {
  $(this).next("div").show();
  }, function () {
  $(this).next("div").hide();
  });

});

想用toggle()控制div的单击显隐,但是这么写为什么一打开页面,标题和div就全渐渐消失了?

 因为。Jquery1.9.1中 toggle(fn1,fn2...)方法 可实现点击一个元素来执行指定函数。此方法被删除以减少混乱和提高潜在的模块化程度。只保留了显示和隐藏的功能!

官网:http://api.jquery.com/toggle/

原始解决方法:全局一个counter=0 click事件中判断counter%2==0 分别触发不同的css,然后counter++,简单粗暴。

或者使用状态机,可以看阮一峰写的文章。

原文地址:https://www.cnblogs.com/youxin/p/3881240.html