【问题标题】:jquery OR selector in complex selector复杂选择器中的jquery OR选择器
【发布时间】:2012-12-13 18:42:21
【问题描述】:

我有以下选择器:

$(".product_tile:nth-child(6n) .tile_back select[name='crust']")

它每 6 个 product_tile 查找一次,然后获取具有 tile_back 类的子 div,然后在其中包含名称为外壳的选择框。我现在需要修改它,以便它找到两个选择框之一 - 外壳或底座。

我知道在基本选择器中,我可以使用逗号:

$("select[name='crust'], select[name='base']")

但是如果我在原始选择器中使用逗号分隔的选择器,它会知道逗号仅适用于它的最后一部分,还是会将其视为“查找每 6 个 product_tile 的 tile_back 的外壳选择框或查找任何选择名为 base 的框”?如果是后者,我该如何编写选择器,使其将其视为“查找每 6 个 product_tile 的 tile_back 的外壳选择框或查找每 6 个 product_tile 的 tile_back 的基本选择框”?

【问题讨论】:

  • 逗号没有做任何特别的事情,它只是将选择器分成两个单独的选择器。尝试尽可能多地选择不带逗号的部分,然后使用 .filter 或 .find 完成带逗号的部分。

标签: jquery jquery-selectors


【解决方案1】:

您可以指定搜索的上下文.. 像这样使用context selector

$("select[name='crust'], select[name='base']",'.product_tile:nth-child(6n) .tile_back')

最初与

相同
$('.product_tile:nth-child(6n) .tile_back').find("select[name='crust'], select[name='base']");

它将在 .product_tile:nth-child(6n) 下找到所有 name=crust 或 name=base 的选择

【讨论】:

    【解决方案2】:

    您将无法将逻辑放入选择器中。您要么必须拥有两个带有逗号的完整选择器:

    $(".product_tile:nth-child(6n) .tile_back select[name='crust'], product_tile:nth-child(6n) .tile_back select[name='base']")
    

    或使用一个选择器匹配直到.tile_back 并使用第二个选择器进行过滤:

    $(".product_tile:nth-child(6n) .tile_back").find("select[name='crust'], select[name='base']")
    

    【讨论】:

      【解决方案3】:

      不,只是在逗号后面加上开头部分:

      $(".product_tile:nth-child(6n) .tile_back select[name='crust'], .product_tile:nth-child(6n) .tile_back select[name='base']")
      

      【讨论】:

        【解决方案4】:

        .add() 方法将选中的元素添加到结果集中:

        $(".product_tile:nth-child(6n) .tile_back").add("select[name='crust']").add("select[name='base']");
        

        【讨论】:

          猜你喜欢
          • 2011-01-16
          • 1970-01-01
          • 2014-09-22
          • 2015-01-25
          • 1970-01-01
          • 2011-02-20
          • 1970-01-01
          相关资源
          最近更新 更多