获取“祖先"的可靠方法具有特定类名的对象,使用 jQuery [英] Reliable way to get the "ancestor" of an object with a specific classname, using jQuery
问题描述
我有一个 javascript 函数,它在选择表单元素的更改事件时被调用.所以,js中的this"变量指的是select元素.
I've got a javascript function that gets called on change event of a select form element. So, the "this" variable in js refers to the select element.
这个 select 元素在 td 标签中,在 tr 标签中.tr 标签的类名为FilterDetailsRow".
This select element is in a td tag, in a tr tag. The tr tag has a classname of "FilterDetailsRow".
现在,我已经测试过了,如果我使用这个语法:
Now, I've tested, and if I use this syntax:
var filterRow = $(this).parent().parent();
它让我得到我想要的.但是,有没有更好的方法来告诉 jQuery,从this"开始,您能否沿着我的父树向上爬,直到找到类名为FilterDetailsRow"的父树?
it gets me what I want. However, is there a better way to tell jQuery, "starting with "this" can you please go up my tree of parents until you find one with a classname of "FilterDetailsRow"?
这是我的想法,但我想确保我不会重新发明轮子.
Here's what I came up with, but I want to make sure I"m not reinventing the wheel.
function GetFilterDetailsRowOfObject(o) {
if (o) {
if (o.parent()[0].className.indexOf("FilterDetailsRow") != -1)
return o;
else
return GetFilterDetailsRowOfObject(o.parent());
} else {
return null;
}
}
感谢您的建议.
推荐答案
您可以使用 closest
找到第一个匹配的祖先:
You can use closest
to find the first matching ancestor:
var filterRow = $(this).closest('.FilterDetailsRow');
这篇关于获取“祖先"的可靠方法具有特定类名的对象,使用 jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!