开发者

The best way to do :not in jQuery?

I have a menu in jQuery when you click on a link it opens up, but I want it so when you click somewhere else, anywhere else that is not the menu, it becomes hidden.

At the moment I'm binding a click event to

$(':not(#the_menu)')

But th开发者_C百科is seems like I'm binding a click event to the entire minus the menu, is there a more efficient way of doing something like this?


The best way to do this is with bubbling capture, like this:

$(document).click(function() {
   //close menu
})

$("#the_menu").click(function(e) {
  e.stopPropagation();
});

How this works is every click bubbles (unless you stop it, usually by return false; or event.stopPopagation()), so whatever you click bubbles all the way up to DOM...if a click does that, we close the menu. If it came from inside the menu, we stop the bubble...so the click doesn't bubble up, triggering a close. This approach uses only 2 event handlers instead of 1 on everything but the menu, so very lightweight :)


Attach event to document's body ($(body)). Also attach another event to #the_menu that's block event propagation:

$(document.body).click(function() {
     //close menu if opened
});

$("#the_menu").click(function(e) {
     //code heere

     e.stopPropagation();
});


How about binding the menu display to hovering over the element in which it is contained?

$("#parentId").hover(
    function() { //!! on hovering in
        $("#targetId").attr("display","block") ;
    } ,
    function() { //!! on hovering out
        $("#targetId").attr("display","none") ;
    }
) ;

If it fits your goal, this seems easier to maintain.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜