【问题标题】:Check whether the checkbox are checked or not检查复选框是否被选中
【发布时间】:2021-07-16 22:36:03
【问题描述】:

我的 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)
        });

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

【问题讨论】:

    标签: javascript angular d3.js angular8 angular9


    【解决方案1】:

    在点击功能中可以通过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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-01
      • 2018-12-17
      • 2014-01-11
      • 2015-06-25
      • 2015-02-09
      • 1970-01-01
      相关资源
      最近更新 更多