jQuery具有"最接近",它返回树中最接近的匹配祖先.是否有Dart等效?我想让以下不那么脆弱:
e.target.parent.parent.nextElementSibling.classes.toggle('hide');
Run Code Online (Sandbox Code Playgroud)
也许是这样的:
e.target.closest('div').nextElementSibling.classes.toggle('hide');
Run Code Online (Sandbox Code Playgroud)
据我所知,没有内置函数。但编写一些代码非常容易。
下面定义的函数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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
408 次 |
| 最近记录: |