2012-06-05 29 views
1

我似乎有另一个问题,我不征服。真正简单的前提。 我有一个mousedown事件,基本上如果页面上的某个特定元素被点击,我不想发生任何事情,否则我想隐藏()一些div。为什么不工作 - 使用:不是()与事件处理程序

$(function(){ 
     $("document :not(#_ignorelement)").mousedown(function(event){ 
       if($('#_hidethiselement').length){ 
        $('#_hidethiselement').hide(); 
       } 
     }) 
    }) 

这根本不起作用。我也试过如下:

$(document).not($("#_ignorelement")).mousedown(function(event){ 

    $(document).not("_ignorelement").mousedown(function(event){ 

如果我能解决这个问题,好奇我怎么会居然有“:不”包括父DIV,像这样:

$().not("_ignoreelement").parent().closest('div').mousedown(function 

由于元素“_ignorelement”是一个div中的锚标签。不知道我可以如何使用父div,而不是锚标签。

无论如何,任何帮助,将不胜感激。

+0

你为什么使用'mousedown'而不是'click'? – FishBasketGordo

+1

我认为你需要在第一个选择器中使用'html'或'body'而不是'document' – Musa

+0

我使用mousedown,因为页面上有一些项目/元素在点击被传播之前被捕获,所以我需要另一种方法来知道点击是否发生,即。鼠标按下。 –

回答

2

document不是您可以选择的节点。试试这个:

$(function(){ 
    $("body :not(#_ignorelement)").mousedown(function(event){ 
     if($('#_hidethiselement').length){ 
      $('#_hidethiselement').hide(); 
     } 
     return false; 
    }) 
}); 

这里有一个working example

+0

它不会工作 - 会触发'body'点击。 – VisioN

+0

感谢您的支持@VisioN。我添加了一个'return false'语句来防止这种情况。 – FishBasketGordo

+0

您还需要取消冒泡。否则,所有的父元素也会收到一个'mouseup'事件。 – powerbuoy

1

这应该工作:

var ignoreNode = jQuery('#_ignorelement')[0]; 

jQuery(document).on('mousedown', function(e) { 
    if (ignoreNode === e.target || jQuery.contains(ignoreNode, e.target)) { 
    // If the target is, or is inside the ignoreNode, don't 
    // do anything. 
    return; 
    } 

    // Do your hiding handling here 
}); 

注意,这确实是一个好主意,缓存您的jQuery的对象,这样你没有运行选择查询每一个事件!

+0

感谢一堆关于提醒缓存它们。这下滑了我的想法。 :_) –

相关问题