将选择器应用于已选择的元素

时间:2018-11-22 12:56:04

标签: javascript jquery html jquery-selectors

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

let tables = $('table');

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

$('table.some-class')

我该怎么办?

2 个答案:

答案 0 :(得分:3)

您需要使用.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>

答案 1 :(得分:0)

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

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

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

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

在您的问题中,尚不清楚您是否需要子元素或仅filter个元素。如果要使用给定类的表,则可以执行以下操作:

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