.not()与.live()不起作用 [英] .not() with .live() not working

查看:67
本文介绍了.not()与.live()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如何使其工作?

推荐答案

尝试将其全部放入主选择器:

Try putting it all in the main selector:

示例: http://jsfiddle.net/8Tkex/

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


使用.not()无效的原因是,当您使用jQuery的live()方法时,实际上并没有在元素上放置点击处理程序.相反,您将其放置在文档的根目录.

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.

之所以可行,是因为页面上的所有click(及其他)事件从实际接收到事件的元素一直冒泡",一直到根为止,从而使用.

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().

由于页面上的每次点击都会发生这种情况,因此jQuery需要知道哪个项目获得了点击,以便可以确定触发哪个(如果有)处理程序.它使用调用.live()时使用的selector来完成此操作.

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().

因此,如果您这样做:

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

... jQuery将"a"选择器与接收到的每个click事件进行比较.

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

因此,当您这样做时:

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

...然后jQuery使用"a:not(div#mnuMain a)"进行比较.

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

但是,如果您这样做

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

...选择器最终看起来像"a.not(div#mnuMain a)",它什么都不匹配,因为<a>元素上没有.not class .

...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.

我认为某些方法可能适用于live(),但是.not()不是其中一种.

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

如果您想知道jQuery对象的选择器是什么样子,请将对象保存到变量中,然后将其记录到控制台中并在内部查看.您将看到jQuery使用的selector属性.

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

这是我从Safari控制台获得的输出.

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

这篇关于.not()与.live()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆