使用 d3 选中/取消选中复选框 [英] checkbox check/uncheck using d3
问题描述
我无法使用 d3 选择来检查和取消选中复选框.以下代码似乎不起作用.我希望在按下选中"时选中所有复选框,并在按下取消选中"时取消选中所有复选框.
I am having difficulty checking and unchecking checkboxes using d3 selection. The following code doesn't seem to work. I want all check boxes to be checked when 'check' is pressed, and all checkboxes unchecked when 'uncheck' is pressed.
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<button type='button' onclick='checkAll()'>Check</button>
<button type='button' onclick='uncheckAll()'>Uncheck</button>
<script src="http://d3js.org/d3.v2.min.js?2.10.0"></script>
<script>
function checkAll(){
d3.selectAll('input').attr('checked','true');
}
function uncheckAll(){
d3.selectAll('input').attr('checked','false');
}
</script>
</body>
推荐答案
使用 property()
而不是 attr()
:
function checkAll() {
d3.selectAll('input').property('checked', true);
}
function uncheckAll() {
d3.selectAll('input').property('checked', false);
}
来自 https://github.com/mbostock/d3/wiki/Selections#wiki-property:
某些 HTML 元素具有使用标准属性或样式无法寻址的特殊属性.例如,表单文本字段具有 value
字符串属性,复选框具有 checked
布尔属性.您可以使用 property
运算符来获取或设置这些属性.
Some HTML elements have special properties that are not addressable using standard attributes or styles. For example, form text fields have a
value
string property, and checkboxes have achecked
boolean property. You can use theproperty
operator to get or set these properties.
这篇关于使用 d3 选中/取消选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!