.not() with .live() not working

2019-03-01 17:52发布

jQuery("a").not("div#mnuMain a").live("click", function(event){
                event.preventDefault();
                alert("yes I got u");                 
        });

How to make it work?

2条回答
欢心
2楼-- · 2019-03-01 18:33

Try putting it all in the main selector:

Example: http://jsfiddle.net/8Tkex/

jQuery("a:not(div#mnuMain a)").live("click", function(event){
            event.preventDefault();
            alert("yes I got u");                 
    });

EDIT:

The reason using .not() didn't work is that when you use jQuery's live() method, you're not actually placing the click handler on the element. Instead you're placing it at the root of the document.

This works because all click (and other) events on the page "bubble up" from the element that actually received the event, all the way up to the root, thus firing the handler that you placed at the root using .live().

Because this occurs for every click on the page, jQuery needs to know which item received the click so it can determine which (if any) handler to fire. It does this using the selector you used when you called .live().

So if you did:

jQuery("a").live("click", func...

...jQuery compares the "a" selector to every click event that is received.

So when you do:

jQuery("a:not(div#mnuMain a)").live("click", func...

...then jQuery uses "a:not(div#mnuMain a)" for the comparison.

But if you do

jQuery("a").not("div#mnuMain a").live("click", func...

...the selector ends up looking like "a.not(div#mnuMain a)", which wouldn't match anything, since there's no .not class on the <a> element.

I think some methods may work with live(), but .not() isn't one of them.

If you're ever curious about what the selector looks like for your jQuery object, save your object to a variable, log it to the console and look inside. You'll see the selector property that jQuery uses.

var $elem = jQuery("a").not("div#mnuMain a");

console.log( $elem );

...should output to the console something like:

Object
     context: HTMLDocument
     length: 0
     prevObject: Object
     selector: "a.not(div#mnuMain a)"  // The selector that jQuery stored
     __proto__: Object

This is the output I get from Safari's console.

查看更多
姐就是有狂的资本
3楼-- · 2019-03-01 18:51
jQuery("a:not(div#mnuMain a)").live("click", function(event){
            event.preventDefault();
            alert("yes I got u");                 
    });

try this

查看更多
登录 后发表回答