Javascript $('html').click()... 除了一个元素之外的任何地方

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9992368/
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-24 12:06:09  来源:igfitidea点击:

$('html').click()... anywhere except one element

javascriptjqueryhtmlclick

提问by devjs11

I have a dynamically appended menu which I am removing if you click anywhere on page including the menu links itself. What I am trying to achieve is to prevent the remove if you click a specific link and that simply does not work for me. Unfortunately I cant use the delegate method, if that would help, due to old version on jquery used on client side, no option to update it.

我有一个动态附加的菜单,如果您单击页面上的任意位置(包括菜单链接本身),我将删除该菜单。我想要实现的是,如果您单击特定链接,则阻止删除,而这对我来说根本不起作用。不幸的是,我不能使用委托方法,如果这有帮助的话,由于客户端使用的 jquery 的旧版本,没有更新它的选项。

So maybe you could suggest if there is any way to do so. Here is a quick example of mine.

所以也许你可以建议是否有任何方法可以这样做。这是我的一个快速示例。

<script>
            $(function() {

                $('.menu').append('<a href="" class="solid">Option</a> <a href="">Option</a> <a href="">Option</a>');                               

                $('.menu a').live('click',function(){
                    return false;
                });

                $('a.solid').live('click',function(){
                    return false;
                });

                $('html').click(function() {                    
                    $('.menu').remove();                
                });             

            });

        </script>

and the container

和容器

<div class="menu"></div>

回答by sneeky

Maybe it will work like this

也许它会像这样工作

$('html').click(function(e) {                    
   if(!$(e.target).hasClass('solid') )
   {
       $('.menu').remove();                
   }
}); 

see: http://jsfiddle.net/fq86U/2/

见:http: //jsfiddle.net/fq86U/2/

回答by huysentruitw

have you tried this:

你有没有试过这个:

$('.menu a').click(function(event){
   event.stopPropagation();
});

回答by pplewa

You can also detect clicks on the whole document and check if the current element clicked is your menu element

您还可以检测对整个文档的点击,并检查点击的当前元素是否是您的菜单元素

$(document).click(function(event){
    if(event.target !== $('.menu')[0]) {
        // hide the menu...
    }
});?

回答by alex

$('html').click(function(e) {

        /* exept elements with class someClass */ 
        if($(e.target).hasClass('someClass')){
            e.preventDefault();
            return;
        }

        /* but be carefull the contained links! to be clickable */
        if($(e.target).is('a')){
            return;
        }

        /* here you can code what to do when click on html */

    });