繁体   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

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

我有一个搜索结果可以正常运行。 仅在用户在结果或搜索框之外单击时,我才在努力获取结果以擦除结果。 以下内容适用,但即使我在搜索框或结果div中单击也清除了结果。 (我想这个问题与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>

我也尝试过:

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

其次,我宁愿仅在包含div上使用该类。 我将如何更改if语句?

我查看了有关该主题的其他文章,这使我走到了这一步。 我快到了

谢谢

将事件对象作为参数添加到回调中,例如$('body')。click(function(e){,然后检查e.target。

由于事件在Javascript中的工作方式,因此您的方法很容易产生不良且不可预测的结果。

使用这个逻辑

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

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

参考

$('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