Nokogiri相当于jQuery nearest()方法,用于在树中查找第一个匹配的祖先 [英] Nokogiri equivalent of jQuery closest() method for finding first matching ancestor in tree
问题描述
jQuery有一个可爱的,如果有点错误的方法,称为最近的(),走向DOM树看用于匹配元素。例如,如果我有这个HTML:
jQuery has a lovely if somewhat misnamed method called closest() that walks up the DOM tree looking for a matching element. For example, if I've got this HTML:
<table src="foo">
<tr>
<td>Yay</td>
</tr>
</table>
假设元素
设置为< td>
,那么我可以这样计算出 src
的值:
Assuming element
is set to <td>
, then I can figure the value of src
like this:
element.closest('table')['src']
如果表元素或其src属性中的任一个缺失,那么它将会干净地返回undefined。
And that will cleanly return "undefined" if either of the table element or its src attribute are missing.
在Javascriptland中习惯了这个'd喜欢在Rubyland找到相当于Nokogiri的东西,但是我能够提出的最接近的是这个明显不合理的黑客使用 ancestors():
Having gotten used to this in Javascriptland, I'd love to find something equivalent for Nokogiri in Rubyland, but the closest I've been able to come up with is this distinctly inelegant hack using ancestors():
ancestors = element.ancestors('table')
src = ancestors.any? ? first['src'] : nil
需要三元组,因为如果在空的阵列。更好的想法?
The ternary is needed because first returns nil if called on an empty array. Better ideas?
推荐答案
您可以在空数组上调用 first
问题是它会返回 nil
,你不能说 nil ['src']
而不会伤心。您可以这样做:
You can call first
on an empty array, the problem is that it will return nil
and you can't say nil['src']
without getting sad. You could do this:
src = (element.ancestors('table').first || { })['src']
如果你在Rails,你可以使用 try
soly:
And if you're in Rails, you could use try
thusly:
src = element.ancestors('table').first.try(:fetch, 'src')
如果你在做这样的事情很多,那么在一个方法:
If you're doing this sort of thing a lot then hide the ugliness in a method:
def closest_attr_from(e, selector, attr)
a = e.closest(selector)
a ? a[attr] : nil
end
然后
src = closest_attr_from(element, 'table', 'src')
您还可以将其修补到Nokogiri :: XML :: Node(但我不会推荐它):
You could also patch it right into Nokogiri::XML::Node (but I wouldn't recommend it):
class Nokogiri::XML::Node
def closest(selector)
ancestors(selector).first
end
def closest_attr(selector, attr)
a = closest(selector)
a ? a[attr] : nil
end
end
这篇关于Nokogiri相当于jQuery nearest()方法,用于在树中查找第一个匹配的祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!