【问题标题】:How do you loop through every Checkbox in Div? (dart)你如何循环遍历 Div 中的每个复选框? (镖)
【发布时间】:2014-08-06 12:05:26
【问题描述】:

我的 html 中有一个 div:

<div id="list_container_id"></div>

我通过 dart 添加复选框

CheckboxInputElement cie = new CheckboxInputElement();
LabelElement label = new LabelElement();
    cie.id="checkboxid_"+asdf;//unique id
    label.htmlFor = 'checkboxid_'+asdf;//bind Label to checkbox
    label.text = asdf;
    list_container.children.add(cie);
    list_container.children.add(label);
    list_container.children.add(new Element.html("<br>"));//linebreak after the checkbox

稍后,我想获取在按钮单击时选中的复选框的所有值的列表。点击时发生如下代码:

List list = [];    
for (CheckboxInputElement elem in list_container.children){
        if(elem.checked){
          list.add(elem.value);
        }
      }

据我了解,for 循环会遍历 list_container 中的每个 Checkbox,但由于某种原因,它在到达标签时会引发错误:

打破异常:类型“LabelElement”不是类型的子类型 'elem' 的'CheckboxInputElement'。

当我清楚地说明 elem 应该是 CheckboxInputElement 时,我不明白为什么 for 循环甚至会打扰标签。这样做的正确方法是什么?

【问题讨论】:

    标签: dart dart-html


    【解决方案1】:

    您没有声明它应该只返回 CheckboxInputElement 您声明保存在循环中处理的值的变量应该只保存 CheckboxInputElements 但循环分配它遇到的每个元素。

    这样你只能得到CheckboxInputElement

    List list = [];    
    for (var elem in list_container.children.where((e) => e is CheckboxInputElement)){
      if(elem.checked){
        list.add(elem.value);
      }
    }
    

    list.addAll(list_container.children
      .where((e) => e is CheckboxInputElement && e.checked)
      .map((e) => e.value));
    

    list.addAll(querySelectorAll('#list_container_id input[type="checkbox"]')
      .where((e) => e is CheckboxInputElement && e.checked)
      .map((e) => e.value));
    

    【讨论】:

      【解决方案2】:
      querySelector("#list_container_id")
          .querySelectorAll("input[type=checkbox]")
              .forEach((CheckboxInputElement e) {
                  /* do work */ 
               });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-20
        • 2012-10-22
        • 1970-01-01
        相关资源
        最近更新 更多