jQuery 如果点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2223956/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:03:16  来源:igfitidea点击:

jQuery if clicked?

jquery

提问by mike

With the following piece of code... Is it possible to say, if the li was clicked do this if not(user click somewhere else) do that? The code will only make the div disappear if the user clicks something in the list. I need it to disappear if they click anywhere else as well... ?? Thanks!

使用以下代码...是否可以说,如果单击 li 则执行此操作,否则(用户单击其他位置)执行此操作?如果用户单击列表中的某些内容,该代码只会使 div 消失。如果他们也点击其他任何地方,我需要它消失......?谢谢!

.bind('blur', function() {
   $('#search_suggestions_list li').click(function() {
       var selectedString = $(this).text();
       $('#search-box').val(selectedString);
       setTimeout("$('#search_suggestions').fadeOut('fast');", 200);
   })
})

回答by munch

$(document).click(function(){
   //user clicked anywhere on the page
});

$('#search_suggestions_list li').click(function() {
   //user clicked on the li
   return false;
});

Make sure to return false, otherwise the document click event will be called as well.

确保返回false,否则文档点击事件也会被调用。

回答by Josh Stodola

Handle the click event on the document, and then handle the click event on your li. Inside the click event for the li, use the stopPropogationfunction to prevent the document (parent) click event from firing...

处理文档上的点击事件,然后处理您的li. 在 的点击事件中li,使用该stopPropogation函数防止文档(父)点击事件触发...

$(document).click(function() {
  // Clicked outside the LI
});

$('#search_suggestions_list li').click(function(e) {
  var selectedString = $(this).text(); 
  $('#search-box').val(selectedString); 
  setTimeout("$('#search_suggestions').fadeOut('fast');", 200);

  e.stopPropagation(); // Stops document.click from firing
}) 

回答by hunter

$('#search_suggestions_list li').click(function() {
   var selectedString = $(this).text();
   $('#search-box').val(selectedString);
   setTimeout("$('#search_suggestions').fadeOut('fast');", 200);
})

$('#search-box').blur(function(){
    // do something else
});