jQuery-通过子类选择父级? [英] jQuery - select parent by child class?

查看:97
本文介绍了jQuery-通过子类选择父级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何选择包含子<div class="test"><tr>,如下所示?

How can I select the <tr> containing the child <div class="test">, as below?

<table>
  <tr> <!-- this tr is what I want to select -->
    <td>
      <div class="test"> text </div>
    </td>
  </tr>
</table>

推荐答案

您可以使用 parents closest ,具体取决于您的需求:

You can use parents or closest for that, depending on your needs:

$("div.test").parents("tr");
// Or
$("div.test").closest("tr");

(初始选择器可以是与您的div相匹配的任何内容,因此".test"也可以.)

(The initial selector can be anything that matches your div, so ".test" would be fine too.)

parents将一直沿树向上移动,如果表中有一个表,则可能与多个tr元素匹配. closest将从每个div遇到的第一个tr停止.

parents will look all the way up the tree, possibly matching multiple tr elements if you have a table within a table. closest will stop with the first tr it encounters for each of the divs.

以下是使用closest的示例:

实时复制 | 实时来源

HTML:

<table>
  <tr id="first"> <!-- this tr I want to select -->
    <td>
      <div class="test"> text </div>
    </td>
  </tr>
  <tr id="second"> <!-- this tr I want to select -->
    <td>
      <div class="test"> text </div>
    </td>
  </tr>
  <tr id="third"> <!-- this tr I want to select -->
    <td>
      <div class="test"> text </div>
    </td>
  </tr>
</table>

JavaScript:

JavaScript:

jQuery(function($) {

  var rows = $("div.test").closest("tr");
  display("Matched " + rows.length + " rows:");
  rows.each(function() {
    display("Row '" + this.id + "'");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

输出:

Matched 3 rows:
Row 'first'
Row 'second'
Row 'third'

这篇关于jQuery-通过子类选择父级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆