代码之家  ›  专栏  ›  技术社区  ›  XDS

使用:not(:not())模拟jQuery中的(假设的):is()选择器

  •  1
  • XDS  · 技术社区  · 8 年前

    我想编写如下jQuery语句:

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

    作为以下的缩写:

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

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

    我确实意识到它在性能方面有缺点,如果。someparentcontainer有大量的子元素,但它对小dom树非常有效。

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

    2 回复  |  直到 8 年前
        1
  •  2
  •   Dekel    8 年前

    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>

    这更有意义。

        2
  •  1
  •   Community CDub    8 年前

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

    因为你已经标记了你的问题 , the standard does not allow :not() to be nested within another :not() A:不是 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? ).