开发者

.not() with .live() not working

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

How to make it work?


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.


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

try this

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜