简体   繁体   English

当用户在div之外单击时,如何使用jQuery this和class影响div

[英]How do I use jQuery this and class to affect a div when the user clicks outside the div

How do I use jQuery this and class to affect a div when the user clicks outside the div 当用户在div之外单击时,如何使用jQuery this和class影响div

I have a search that I built that works. 我有一个搜索结果可以正常运行。 I'm stuggling with getting the results to erase the results Only when the user clicks outside of the results or the search box. 仅在用户在结果或搜索框之外单击时,我才在努力获取结果以擦除结果。 The following works with the exception that it wipes out the results even if I click IN the search box or the results div. 以下内容适用,但即使我在搜索框或结果div中单击也清除了结果。 (I imagine that the issue is related to "this" reference in the if statement.) (我想这个问题与if语句中的“ this”引用有关。)

$('#searchbox').keyup(function(){
  $.post("remote.php",{'func':'contactsearch','partial':this.value},function(data){
    $("#results").html(data);
     // erase the results when user clicks outside the search
     $('body').click(function(){
       if (!$(this).hasClass('nd_search')) { // erases results even when clicked inside result - why?
         $("#results").html('');
         $('body').unbind('click'); // remove event handler. add again when results shown.
        }
    });
   });
  });       
});

<div class="nd_search">
    <input id="searchbox" type="text" class="nd_search"/>
    <div id="results" class="nd_search"></div>
</div>

I also tried: 我也尝试过:

 $('body').click(function(event){
    if (!$(event.target).hasClass('nd_search')) { ...

Secondarily, I would rather have the class on only the containing div. 其次,我宁愿仅在包含div上使用该类。 How would I change the if statement? 我将如何更改if语句?

I looked at the other posts about this subject, which got me this far. 我查看了有关该主题的其他文章,这使我走到了这一步。 I'm almost there 我快到了

Thanks 谢谢

Put the event object in as a parameter to your callback, eg $('body').click(function(e) { and then check e.target instead. 将事件对象作为参数添加到回调中,例如$('body')。click(function(e){,然后检查e.target。

Due to the way events work in Javascript, your method can easily produce undesirable and unpredictable results. 由于事件在Javascript中的工作方式,因此您的方法很容易产生不良且不可预测的结果。

use this logic 使用这个逻辑

 $('body').click(function() {
 //Hide the menus if visible
 });

 $('#menucontainer').click(function(event){
     event.stopPropagation();
 });

Reference 参考

$('body').click(function(evt) {
if($(evt.target).parents('.nd_search').length==0) {
    $("#results").html('');

}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM