文档点击不在元素jQuery中 [英] Document click not in elements jQuery
问题描述
使用jQuery如何检测点击不在特定元素上,然后执行操作?
Using jQuery how does one detect clicks not on specific elements, and perform an action consequently?
我有以下JavaScript
I have the following JavaScript
$('#master').click(function() {
$('#slave').toggle();
});
$(document).not('#master','#slave').click(function() {
$('#slave').hide();
});
并且我无法看到我的逻辑错误。您可以在此处看到一个实际示例
and I cannot see where I am going wrong logically. You can see a live example here
推荐答案
由于您绑定了文档中的事件,请点击
事件,您可以使用 event.target 来获取启动事件的元素:
Since you're binding to the click
event on the document, you can use event.target to get the element that initiated the event:
$(document).click(function(event) {
if (!$(event.target).is("#master, #slave")) {
$("#slave").hide();
}
});
编辑:正如Mattias在他的评论中正确指出的那样,将无法识别来自 #master
和 #slave
(如果有)的后代的点击事件。在这种情况下,您可以使用最接近的()来检查事件的目标:
As Mattias rightfully points out in his comment, the code above will fail to identify click events coming from descendants of #master
and #slave
(if there are any). In this situation, you can use closest() to check the event's target:
$(document).click(function(event) {
if (!$(event.target).closest("#master, #slave").length) {
$("#slave").hide();
}
});
这篇关于文档点击不在元素jQuery中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!