jQuery 有“closest”,它返回树中最接近的匹配祖先。有 Dart 等价物吗?我想让以下内容不那么脆弱:
e.target.parent.parent.nextElementSibling.classes.toggle('hide');
也许是这样的:
e.target.closest('div').nextElementSibling.classes.toggle('hide');
jQuery 有“closest”,它返回树中最接近的匹配祖先。有 Dart 等价物吗?我想让以下内容不那么脆弱:
e.target.parent.parent.nextElementSibling.classes.toggle('hide');
也许是这样的:
e.target.closest('div').nextElementSibling.classes.toggle('hide');
据我所知,没有内置函数。但是编写一些东西很容易。
下面findClosestAncestor()
定义的函数查找给定祖先标签的元素的壁橱祖先:
<!DOCTYPE html>
<html>
<head>
<title>ancestor</title>
</head>
<body>
<div id='outer'>
<div id='inner'>
<p></p>
</div>
</div>
<script type="application/dart">
import 'dart:html';
Element findClosestAncestor(element, ancestorTagName) {
Element parent = element.parent;
while (parent.tagName.toLowerCase() != ancestorTagName.toLowerCase()) {
parent = parent.parent;
if (parent == null) {
// Throw, or find some other way to handle the tagName not being found.
throw '$ancestorTagName not found';
}
}
return parent;
}
void main() {
ParagraphElement p = query('p');
Element parent = findClosestAncestor(p, 'div');
print(parent.id); // 'inner'
}
</script>
<script src="packages/browser/dart.js"></script>
</body>
</html>