.not() with .live() not working

做~自己de王妃 提交于 2019-12-31 04:56:07

问题


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

How to make it work?


回答1:


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.




回答2:


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

try this



来源:https://stackoverflow.com/questions/3635471/not-with-live-not-working

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