在jquery中访问父级的最快方法

时间:2012-04-26 21:06:02

标签: jquery

我需要为具有类“tableClass”的表分配样式。我有以下标记。

<table border="0" cellpadding="0" cellspacing="0" class="tableClass">
  <tr>
    <td>
    <table border="0" cellpadding="0" cellspacing="0" class="tableClass"> <-- Need to add a style here
      <tr class="colheadrowclass">
        .. some markup here
      </tr>
      more markup
      <tr id="dataRow" class="datarowclass">
      </tr>
    </table>
    </td>
  </tr>
</table>

datarowclass开始,我需要遍历第一个包含类tableClass的表并为其添加样式。

这适合我,但我想知道是否有更快的方式。

$(".datarowclass").parents("table").eq(0).css("hieght", "500px");

2 个答案:

答案 0 :(得分:1)

以下内容可以帮助您:

$('.datarowclass').closest('table.tableClass').css("height", "500px");

它完全符合您的提及:

  1. 选择datarowclass类的元素。
  2. 从中(第1点中找到的元素)搜索最近的table tableClass类,
  3. 更改第2点中找到的元素的样式。
  4. 注意:“height”属性中有拼写错误(您将其拼写错误为“hieght”)。

答案 1 :(得分:0)

尝试使用.closest()并删除.eq(0)

$(".datarowclass").closest("table").css("hieght", "500px");