我无法使用d3选项检查和取消选中复选框。以下代码似乎不起作用。我希望在按下'check'时检查所有复选框,并在按下'uncheck'时取消选中所有复选框。
<!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>
答案 0 :(得分:31)
使用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
运算符来获取或设置这些属性。
答案 1 :(得分:2)
更改您的uncheckAll
功能,将checked
属性设置为null
,而不是false
:
function uncheckAll(){
d3.selectAll('input').attr('checked',null);
}
checked属性存在,可选择设置为checked="checked"
,或者不存在(根本没有检查属性)。将其设置为null
将删除该属性,在这种情况下。
答案 2 :(得分:2)
您需要做的是更新元素的选中值,如下所示:
d3.selectAll("input").each(function(d){
if(d3.select(this).attr("type") == "checkbox")
d3.select(this).node().checked = true;
});
这将确保仅更改所有复选框状态
答案 3 :(得分:1)
您可以通过过滤类型属性
上的选项,将您的选择限制为仅限复选框d3.selectAll("input[type=checkbox]").property("checked", true);
这可以避免在存在的非复选框输入上设置checked属性。