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

孤者浪人 提交于 2019-12-20 11:32:18

问题


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.

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>

回答1:


Maybe it will work like this

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

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




回答2:


have you tried this:

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



回答3:


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...
    }
});​



回答4:


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

    });


来源:https://stackoverflow.com/questions/9992368/html-click-anywhere-except-one-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!