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

checkbox check/uncheck using d3

本文关键字:复选框 取消 D3 选中 使用      更新时间:2023-09-26

我在使用 d3 选择时难以选中和取消选中复选框。以下代码似乎不起作用。我希望在按下"选中"时选中所有复选框,并在按下"取消选中"时取消选中所有复选框。

<!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 运算符获取或设置这些属性。

您可以通过在 type 属性上筛选选择来将选择限制为仅复选框,

d3.selectAll("input[type=checkbox]").property("checked", true);

这样可以避免在存在的非复选框输入上设置选中属性。

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

function uncheckAll(){
    d3.selectAll('input').attr('checked',null);
}

选中的属性要么存在,可以选择设置为 checked="checked" ,要么不存在(根本没有选中的属性)。 在这种情况下,将其设置为 null 将删除该属性。

您需要

做的是更新元素的检查值,如下所示:

d3.selectAll("input").each(function(d){ 
  if(d3.select(this).attr("type") == "checkbox") 
    d3.select(this).node().checked = true;
});

这将确保仅更改所有复选框状态