如何使用 jQuery 找到 td 的父 tr?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11590792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:45:48  来源:igfitidea点击:

How can I find the parent tr of a td using jQuery?

jquery

提问by Alan2

I have the following:

我有以下几点:

    tdToPad = tds.filter('[id^="input_Title_"]')
    pad = 60;
    tdToPad.css('margin-left', pad);

What I would like to do is to remove any class that starts with "X-" and give the row that is contained by "tdToPad" a class of "X-" + pad.

我想要做的是删除任何以“X-”开头的类,并给“tdToPad”包含的行一个“X-”+ pad 的类。

Something like:

就像是:

<tr class='X-60'>
   <td>
   </td>
</tr>

Being that toToPad refers to the td element in a row. How can I give the parent tr the class "X-" + pad ? I think I need something like the following but if that's the correct way to do it then how can I remove elements already there with a class of "X-" somevalue and then give this element the correct class?

因为 toToPad 指的是一行中的 td 元素。我怎样才能给父母 tr 班级 "X-" + pad ?我想我需要像下面这样的东西,但如果这是正确的方法,那么我如何使用“X-” somevalue 类删除已经存在的元素,然后给这个元素提供正确的类?

tdToPad.Parent('tr')

回答by undefined

You can use closest()method:

您可以使用closest()方法:

Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

获取与选择器匹配的第一个元素,从当前元素开始并向上遍历 DOM 树。

tdToPad.closest('tr')
       .addClass('X-' + pad)

update:

更新:

tdToPad.closest('tr').get(0).className = tdToPad.closest('tr').get(0).className.replace(/\bX\-.*?\b/g, '');
tdToPad.closest('tr').addClass('X-' + pad)

回答by Sirko

You're almost right. Just use the correct spelling for parent()(docu) and add a addClass()(docu) call to it.

你几乎是对的。只需为parent()( docu)使用正确的拼写并添加一个addClass()( docu) 调用即可。

tdToPad.parent('tr').addClass( 'X-' + pad );