【问题标题】:Apply selector to elements that have already been selected将选择器应用于已经被选中的元素
【发布时间】:2018-11-22 12:56:04
【问题描述】:

我觉得我在问一些非常愚蠢的问题,但也许这不是我的日子。如果我已经有一个选定的元素,例如:

let tables = $('table');

但现在我想在 tables 之上应用另一个选择器,如 .some-class,但不创建像这样的新 jQuery 对象

$('table.some-class')

我该怎么做?

【问题讨论】:

  • 可能像$(tables+'.some-class');
  • find()怎么样
  • @AnkitAgarwal $('table').find('.some-class')$('table.some-class')不同

标签: javascript jquery html jquery-selectors


【解决方案1】:

您需要使用.filter() 为变量选择器添加过滤器。

let tables = $('table');
tables = tables.filter('.some-class');
tables.css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>table</td>
  </tr>
</table>
<table class="some-class">
  <tr>
    <td>table has .some-class</td>
  </tr>
</table>

【讨论】:

    【解决方案2】:

    使用以下代码,您可以在标签名称为table 的元素下find 类为.some-class 的所有元素。

    let tables = $('table').find('.some-class');
    

    当然,这只是示例,否则你可以简单地这样做:

    let tables = $('table .some-class');
    

    在您的问题中,不清楚您是想要子元素还是只想要 filter 元素。如果你想要具有给定类的表,你会这样做:

    let tables = $('table').filter('.some-class');
    

    【讨论】:

    • 我从未提及儿童元素。我正在尝试将选择器应用于原始元素。
    猜你喜欢
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多