复选框使用d3选中/取消选中

use*_*165 16 javascript checkbox d3.js

我在使用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>
Run Code Online (Sandbox Code Playgroud)

Mar*_*cok 34

使用property()而不是attr():

function checkAll() {
    d3.selectAll('input').property('checked', true);
}
function uncheckAll() {
    d3.selectAll('input').property('checked', false);
}
Run Code Online (Sandbox Code Playgroud)

来自https://github.com/mbostock/d3/wiki/Selections#wiki-property:

某些HTML元素具有使用标准属性或样式无法寻址的特殊属性.例如,表单文本字段具有value字符串属性,而复选框具有checked布尔属性.您可以使用property运算符来获取或设置这些属性.


Jef*_*son 3

更改您的uncheckAll函数以将checked属性设置为null而不是false

function uncheckAll(){
    d3.selectAll('input').attr('checked',null);
}
Run Code Online (Sandbox Code Playgroud)

checked 属性要么存在,可选地设置为checked="checked",要么不存在(根本没有checked 属性)。在本例中,将其设置为null将删除该属性。