我的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
稍后,我想获得在单击按钮时选中的复选框的所有值的列表。以下代码发生在onClick上:
List list = [];
for (CheckboxInputElement elem in list_container.children){
if(elem.checked){
list.add(elem.value);
}
}
据我了解,for循环通过list_container中的每个Checkbox,但是由于某种原因,到达标签时会引发错误:
Breaking on exception: type 'LabelElement' is not a subtype of type 'CheckboxInputElement' of 'elem'.
我不明白为什么当我明确指出elem应该是CheckboxInputElement时,for循环还会困扰Labels。如何做到这一点的正确方法?
最佳答案
您没有声明仅返回CheckboxInputElement
,而是声明包含在循环中处理的值的变量仅应保留CheckboxInputElement
,但循环会分配它遇到的每个元素。
这样你只得到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));
关于dart - 如何遍历Div中的每个复选框? ( Dart ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25159958/