在Dart中有相当于jquery的“最接近”

时间:2013-05-08 16:46:20

标签: dart

jQuery具有“最接近”,它返回树中最接近的匹配祖先。是否有Dart等效?我想让以下内容不那么脆弱:

e.target.parent.parent.nextElementSibling.classes.toggle('hide');

可能是这样的:

e.target.closest('div').nextElementSibling.classes.toggle('hide');

1 个答案:

答案 0 :(得分:4)

据我所知,没有内置功能。但是编写代码很容易。

下面定义的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>
相关问题