且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

点击显示/隐藏点击jQuery

更新时间:2023-11-30 14:42:58

版本1.8中不推荐使用toggle事件,版本1.9中删除了该事件



试试这个......

The toggle-event is deprecated in version 1.8, and removed in version 1.9

Try this...

$('#myelement').toggle(
   function () {
      $('#another-element').show("slide", {
          direction: "right"
      }, 1000);
   },
   function () {
      $('#another-element').hide("slide", {
          direction: "right"
      }, 1000);
});


注意:此方法签名在jQuery 1.8中已弃用,在jQuery 1.9中已删除。 jQuery还提供了一个名为
.toggle()的动画方法,可以切换元素的可见性。
动画或事件方法是否被触发取决于
传递的参数集, jQuery docs

Note: This method signature was deprecated in jQuery 1.8 and removed in jQuery 1.9. jQuery also provides an animation method named .toggle() that toggles the visibility of elements. Whether the animation or the event method is fired depends on the set of arguments passed, jQuery docs.

提供.toggle()方法是为了方便起见。手动实现相同的行为直接相对
,如果.toggle()中内置的假设证明是有限的,那么这可能是

例如,如果将
两次应用于同一元素,则无法保证.toggle()无法正常工作。由于.toggle()在内部使用单击
处理程序来完成其工作,我们必须解除绑定以删除附加.toggle()的行为
,以便其他点击处理程序可以在$ b $中捕获b交火。该实现还在
事件上调用.preventDefault(),因此如果在元素上调用了.toggle(),则不会遵循链接并且不会单击按钮
jQuery docs

The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element, jQuery docs

你使用show显示可见性,使用click进行隐藏。如果元素可见则可以将条件置于可见性上,然后隐藏其他显示它。 请注意,您需要 jQuery UI 使用显示/隐藏方向添加效果

You toggle between visibility using show and hide with click. You can put condition on visibility if element is visible then hide else show it. Note you will need jQuery UI to use addition effects with show / hide like direction.

现场演示

Live Demo

$( "#myelement" ).click(function() {     
    if($('#another-element:visible').length)
        $('#another-element').hide("slide", { direction: "right" }, 1000);
    else
        $('#another-element').show("slide", { direction: "right" }, 1000);        
});

或者,只需使用切换而不是点击。通过使用切换,您不需要条件(if-else)语句。正如TJCrowder所建议的那样。

Or, simply use toggle instead of click. By using toggle you wont need a condition (if-else) statement. as suggested by T.J.Crowder.

现场演示

Live Demo

$( "#myelement" ).click(function() {     
   $('#another-element').toggle("slide", { direction: "right" }, 1000);
});