按属性选择元素后代

时间:2014-06-09 12:50:08

标签: dart dart-html

在下面的html中我想按属性名称

选择视图标记的后代
<view data-context="testviewmodel">
       <div>
         id:<input data-bind-two-way="model.id">
         name:<input data-bind-two-way="model.name">
         description:<input data-bind-two-way="model.description">
       </div>

       <div>
         id:<input data-bind-two-way="model.id">
         name:<input data-bind-two-way="model.name"> 
         description<input data-bind-two-way="model.description"> 
       </div>

       <div>
         <p>{{model.id}}</p>
         <p>{{model.name}}</p>
         <p>{{model.description}}</p>
       </div>           
    </view>

所以我应该得到6个元素(6个输入元素具有属性data-bind-two-way)然而我写了下面的递归函数,它给了我一个3个元素的列表,这是前三个后代输入元素

 static List<Element> decendantSelector(Element rootElement,{List<Element> collectedElements:null,
                                                       List<String> targetAttributes:null,
                                                       bool mustHaveAllAttributes:false}){

    if(collectedElements==null)
      collectedElements = new List<Element>();


    for(Element child in rootElement.children){
      bool haveAllAttributesFlag = true;
      for(String attrName in targetAttributes){
        if(child.attributes.containsKey(attrName)){
          collectedElements.add(child);
        } else {
          haveAllAttributesFlag = false;
        }
        if(!haveAllAttributesFlag && mustHaveAllAttributes)
          break;
      }
      if(child.hasChildNodes())
          return  decendantSelector(child,
              collectedElements:collectedElements,
              targetAttributes:targetAttributes,
              mustHaveAllAttributes:false);
    }
    return collectedElements;
  }

用它作为

List<Element> descendantsWithAttributeDataBindTwoWay = decendantSelector(querySelector('view'),targetAttributes:['data-bind-two-way']);

任何想法为什么第二个div中的后代被忽略了?

1 个答案:

答案 0 :(得分:1)

这是因为这个退货声明

if(child.hasChildNodes())
          return  decendantSelector(child,

只删除return,它会有用。

您是否考虑过像

这样的内容
Set<Element> result = new Set<Element>();
result.addAll(querySelectorAll('view [data-bind-two-way]'));
// repeat the same with other combinations until you have covered all cases