【问题标题】:jQuery problem with a blur event模糊事件的jQuery问题
【发布时间】:2009-12-03 23:23:04
【问题描述】:

这是我的问题:

我有一个 div 元素,当它被点击时,另一个 div 会出现。现在我不知道如何在页面上单击任何位置,这个 div 就会被删除。我的意思是,我知道如何删除它,但是我应该考虑什么样的事件来做这样的事情!?我不能用焦点/模糊来做到这一点。我的意思是我试过但它不起作用所以我猜不是。可能这很简单,但我想我对此很陌生......

干杯

【问题讨论】:

    标签: jquery events dom


    【解决方案1】:

    当您将其添加到 DOM 时,您还可以创建一次性单击事件处理程序并将其附加到文档中。类似的东西

    // <div> has just been added to the DOM
    $(document).one("click", function() { $('#theDiv').remove(); }); 
    

    这是 Working Demo。将 /edit 添加到 URL 以查看代码

    【讨论】:

    • 谢谢,但我刚刚尝试了那个解决方案,问题是在我点击第一个 div 的同时触发了一次点击事件。
    • 这是因为在单击 &lt;div&gt; 元素后,事件会在 DOM 中冒泡。您需要return false 或使用event.preventDefault();
    【解决方案2】:

    我看到了different question today,但它包含了类似的机制。

    基本上,您希望将点击处理程序附加到document,但只有在点击不是源自某些对象时才会触发它:

    使用此 HTML:

    <div id="menu">Click Me</div>
    <div id="other-popup"> Wow, I have been shown!</div>
    

    使用这个(或类似的东西):

    $(document).click(function(e){
       var $target = $(e.target);
       // For all clicks except those in the menu or the popup, hide the popup
       if(!$target.closest("#menu").length && !$target.closest("#other-popup").length ){
          $("#other-popup").hide();
       }
    });
    

    closest() 在当前节点寻找匹配的祖先节点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      相关资源
      最近更新 更多