简体   繁体   English

为什么 jQuery :not selector 属性不适用于这种情况?

[英]Why jQuery :not selector attribute doesn't work for this scenario?

I have following code which works as expected:我有以下代码按预期工作:

First Approach第一种方法

 $('ul').on('click', function(e) { $(this).append('<li>foo</li>'); }) .on('click', 'li', function(e) { e.stopPropagation(); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul>
What it does is simple: 它的作用很简单:

  • It adds one li element when any bullet point is clicked单击任何项​​目符号时,它会添加一个 li 元素
  • Ignores any click inside li elements忽略 li 元素内的任何点击

I'm cool with that is the behavior I want.我很酷,这就是我想要的行为。 With this approach It seems like bullet points are not part of the li elements because any click performed on the bullet points are not going trough the second function.使用这种方法似乎项目符号不是 li 元素的一部分,因为对项目符号执行的任何点击都不会通过第二个函数。

My problem raised after I thought that I could refactor the javascript code a little bit, passing it a ":not(li)" selector as parameter in the first call.在我认为可以稍微重构 javascript 代码,在第一次调用中将“:not(li)”选择器作为参数传递给它之后,我的问题就出现了。

Second Approach :第二种方法

 $('ul').on('click', ":not(li)", function(e) { $(this).append('<li>foo</li>'); });

But it turned out that is behaving different, I don't understand why is not adding li elements after bullet points are clicked.但事实证明,行为有所不同,我不明白为什么在单击项目符号后不添加 li 元素。

Second approach looks cleaner but opposite of what we saw in the first approach, is like the bullets point were part of the li elements.第二种方法看起来更干净,但与我们在第一种方法中看到的相反,就像项目符号点是 li 元素的一部分。

-Why the second approach is behaving different? - 为什么第二种方法表现不同?

It's because ul :not(li) will select any descendants of a ul that is not a li element.这是因为ul :not(li)将选择不是li元素的ul任何后代。

Since your ul element only contains li elements, the event never gets fired.由于您的ul元素仅包含li元素,因此该事件永远不会被触发。 However, if the li elements contained a span element, the event would get fired when clicking on the span element, but that isn't the desired result.但是,如果li元素包含span元素,则在单击span元素时会触发该事件,但这不是预期的结果。

Rather than suppressing the event when clicking on an li element, I'd simply suggest checking if this is equal to e.target .与其在单击li元素时抑制该事件,不如建议检查this是否等于e.target This is similar to your first example.这类似于您的第一个示例。

 $('ul').on('click', function(e) { if (this === e.target) { $(this).append('<li>foo</li>'); } });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li>A</li> <li>B</li> <li>C</li> </ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM