【问题标题】:Using :not(:not()) to emulate (the hypothetical) :is() selector in jQuery使用 :not(:not()) 在 jQuery 中模拟(假设的):is() 选择器
【发布时间】:2017-02-12 18:40:47
【问题描述】:

我想编写如下 jQuery 语句:

$(".someparentcontainer input[type=checkbox]:is(.foo, .bar, .xyz)")

作为以下的简写:

$(".someparentcontainer input[type=checkbox].foo, .someparentcontainer input[type=checkbox].bar, .someparentcontainer input[type=checkbox].xyz)")

由于 jQuery 不支持(据我所知)一个 :is() 选择器,我想出了以下解决方法:

$(".someparentcontainer input[type=checkbox]:not(:not(.foo, .bar, .xyz))")

我确实意识到,如果 .someparentcontainer 有大量子元素,它在性能方面存在缺陷,但它对于小型 dom-trees 非常有效。

这里有没有我可能遗漏的陷阱?这种技术可能会失败的任何场景?

【问题讨论】:

标签: javascript jquery jquery-selectors css-selectors


【解决方案1】:

可以使用jquery的find函数:

$("#someparentcontainer").find("#foo, #bar, #xyz").css('color', 'red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someparentcontainer">
  <div id="foo">foo</div>
  <div id="bar">bar</div>
  <div id="abc">abc</div>
</div>
<div id="xyz">xyz</div>

这更有意义。

【讨论】:

  • +1 获取有关查找的提示。然而,当/如果涉及实用功能时,如果所述功能需要一个统一的选择器,将选择器分成两部分会带来一些问题。如果上述实用功能是第三方库的一部分,事情肯定会变得更加困难。 .find() 方法有其优势,但价格与使用 :not(:not()) 相似。如果我遗漏了什么,请随时给我提示。
【解决方案2】:

这里有没有我可能遗漏的陷阱?这种技术可能会失败的任何场景?

正如您已将问题标记为 the standard does not allow :not() to be nested within another :not()。标准中每个已知的:not() 实现都正确地将您拥有的内容视为无效。如果 jQuery 允许这样做(如果这样做我不能说我很惊讶),那么这是非标准的,你需要非常小心不要在 jQuery 之外依赖它(例如,它不会在querySelectorAll(),或在 CSS 中)。

推荐的方法是改用.filter()

// If you know that the element with any of these ids is always a checkbox,
// substitute ".someparentcontainer *" for the second selector string
$(".someparentcontainer input[type=checkbox]").filter(".foo, .bar, .xyz")

但这意味着您必须编写两个单独的选择器字符串。再说一次,在选择器 4 的 :matches() 无论如何实现之前,没有办法使用单个符合标准的复杂选择器来执行此操作(请参阅 Does jQuery have something like the :any or :matches pseudo-class?)。

【讨论】:

  • 我猜你的回答总结了人们应该注意的一个地雷。所以我会接受它作为答案。感谢您的洞察力!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-17
  • 2016-09-05
  • 1970-01-01
  • 2011-10-31
  • 2013-05-14
  • 1970-01-01
  • 2011-09-04
相关资源
最近更新 更多