【问题标题】:Jquery and Hide a div on a clickJquery和点击隐藏一个div
【发布时间】:2011-02-12 06:03:30
【问题描述】:

JQuery 有点问题。

好吧,我有一个并且我想在用户单击一个区域时隐藏这个 div,而该区域与 facebook 中的“通知”行为不同。

我找到的解决方案是使用 jQuery.live() 方法,但我认为有更好的方法。

谢谢。

【问题讨论】:

    标签: jquery html click hide


    【解决方案1】:

    假设:

    <div class="notification">You have 3 new messages</div>
    

    使用:

    $(document).click(function(evt) {
      if ($(this).closest("div.notification").length == 0) {
        $("div.notification").fadeOut();
      }
    });
    

    基本上这会监听所有点击。如果收到一个通知 div 中没有出现的消息,它会将它们淡出。

    【讨论】:

    • 如果点击div.notification本身会发生什么?
    • @rahul 不得不对这种情况进行轻微的修正(parents()closest()),但基本上点击后它们不会淡出。
    【解决方案2】:

    感谢您的回答,但是:

    $(this).closest("div.notification").length == 0) 
    

    总是返回 0(即使我在 div 中单击),所以 div 总是隐藏的。

    这是我的代码:

    $(document).click(function(evt) {
            if ($(this).closest("div#show_notif").length==0)
                $("div#show_notif").fadeOut();
    });
    

    还有html:

    <div id="click_show_notif" onclick="$('div#show_notif').show();"><img src="http://'+STATIC_SERVER+'/images/notif.png" /><div id="show_notif"></div>
    

    我忘记了什么?

    【讨论】:

      【解决方案3】:

      试试这个:

      $("#click_show_notif").live('click',function(e) {
          $("#show_notif").show();
          return false;
      });
      
      $('body').live('click',function(e) {
          if ($(this).closest("div#show_notif").length==0) {
              $("div#show_notif").hide();
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2010-11-08
        • 2013-10-30
        • 1970-01-01
        • 2014-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-15
        • 1970-01-01
        相关资源
        最近更新 更多