检查复选框是否被选中

时间:2021-04-22 17:01:08

标签: javascript angular d3.js angular8 angular9

我的 d3 树中有复选框。我的代码如下。

 nodeEnter.append('foreignObject').attr('width', '20')
        .attr("x", 200 / 2)
        .attr("y", 1)
        .attr('height', '20').append('xhtml:input')
        .attr('type', 'checkbox')
        // An on click function for the checkboxes
        .on("click",function(d){
            console.log(d)
        });

从此代码中,我可以在单击复选框时捕获数据。但是有了这个,我想知道是否选中了复选框。我该怎么做?

1 个答案:

答案 0 :(得分:0)

在点击函数中可以通过this访问被点击的节点,查看是否被this.checked选中

.on("click",function(d){
   var check = this.checked;
   console.log(check,d);             
});

或者,您可以使用 d3 来实现与 d3.select(this).property("checked"); 相同的事情,因为您使用的是 d3v5 或更早版本,您也可以按如下方式访问被点击的节点:

.on("click",function(d,i,nodes){
        var check = nodes[i].checked;
        console.log(check,d);             

    });

这是第一种方法:

var svg = d3.select("body")
  .append("svg")
  .attr("width", 400)
  .attr("height", 300);
  
var data = [1,2];

var nodeEnter = svg.selectAll(null)
  .data(data)
  .enter();

nodeEnter.append('foreignObject').attr('width', '20')
        .attr("x", (d,i) => i*50+50)
        .attr("y", 1)
        .attr('height', '20').append('xhtml:input')
        .attr('type', 'checkbox')
        // An on click function for the checkboxes
        .on("click",function(d){
            var check = this.checked;
            console.log(check,d);             

        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>