Bha*_*til 1 jquery jquery-selectors
jQuery("a").not("div#mnuMain a").live("click", function(event){
event.preventDefault();
alert("yes I got u");
});
Run Code Online (Sandbox Code Playgroud)
如何使它工作?
尝试将它全部放在主选择器中:
示例: http ://jsfiddle.net/8Tkex/
jQuery("a:not(div#mnuMain a)").live("click", function(event){
event.preventDefault();
alert("yes I got u");
});
Run Code Online (Sandbox Code Playgroud)
编辑:
使用.not()不起作用的原因是当你使用jQuery的live()方法时,你实际上并没有将click处理程序放在元素上.相反,您将它放在文档的根目录下.
这是有效的,因为页面上的所有单击(和其他)事件都从实际接收事件的元素"冒泡",一直到根,从而触发您在根目录下使用的处理程序.live().
因为在页面上的每次单击都会发生这种情况,所以jQuery需要知道哪个项目收到了点击,因此它可以确定触发哪个(如果有的话)处理程序.它使用selector您在调用时使用的方式执行此操作.live().
所以,如果你这样做:
jQuery("a").live("click", func...
Run Code Online (Sandbox Code Playgroud)
... jQuery将"a"选择器与click收到的每个事件进行比较.
所以当你这样做时:
jQuery("a:not(div#mnuMain a)").live("click", func...
Run Code Online (Sandbox Code Playgroud)
...然后jQuery "a:not(div#mnuMain a)"用于比较.
但如果你这样做
jQuery("a").not("div#mnuMain a").live("click", func...
Run Code Online (Sandbox Code Playgroud)
...选择最终看起来像"a.not(div#mnuMain a)",这将不符合任何东西,因为没有.not 阶级上<a>的元素.
我认为有些方法可以使用live(),但.not()不是其中之一.
如果您对jQuery对象的选择器看起来很好奇,请将对象保存到变量,将其记录到控制台并查看内部.你会看到selectorjQuery使用的属性.
var $elem = jQuery("a").not("div#mnuMain a");
console.log( $elem );
Run Code Online (Sandbox Code Playgroud)
...应该向控制台输出如下内容:
Object
context: HTMLDocument
length: 0
prevObject: Object
selector: "a.not(div#mnuMain a)" // The selector that jQuery stored
__proto__: Object
Run Code Online (Sandbox Code Playgroud)
这是我从Safari的控制台获得的输出.