按属性选择d3.js数据元素

Select d3.js data element by attribute

本文关键字:数据 元素 js d3 属性 选择      更新时间:2023-09-26

我有一个使用d3.js和svg表示的网格。我想做的是在单击瓷砖时更改瓷砖和所有相邻瓷砖的颜色。我想知道选择与单击的瓷砖相邻的瓷砖的最佳方式。到目前为止我的代码:

var w = 960,
    h = 500,
    z = 20,
    x = w / z,
    y = h / z;
var svg = d3.select("body").append("svg")
    .attr("width", w)
    .attr("height", h);
svg.selectAll("rect")
    .data(d3.range(x * y))
  .enter().append("rect")
    .attr("transform", translate)
    .attr("position", pos)
    .attr("width", z)
    .attr("height", z)
    .attr("clicked", false)
    //.on("mouseover", mouseover)
    .on("click", click)
    .style("stroke", "rgb(6,120,155)")
    .style("stroke-width", 2);
    .style("fill", "rgb(255, 255, 255)")

function translate(d) {
  return "translate(" + (d % x) * z + "," + Math.floor(d / x) * z + ")";
}
function pos(d) {
  return [ (d % x) * z , Math.floor(d / x) * z ];
}
function click(d) {
  var currentColor = this.style.fill;
  var clickedYet = d3.select(this).attr("clicked");
  currentColor = currentColor == "rgb(255, 255, 255)" ? "rgb(255, 0, 255)" : "rgb(255, 255, 255)";

  d3.select(this)
    .attr("clicked", true)
    .transition()
      .style("fill", currentColor);
}

我想知道的是,是否可以通过属性位置选择瓷砖/"矩形"?或者我是否应该考虑一种完全不同的方法?

您可以这样做(选择同一行中的所有矩形)

为了更好地理解算法,我对代码进行了注释。

function click(d) {
  var currentColor = this.style.fill;
  //this will give the data associated with the rectangle
  var clickeddata = d3.select(this).data();
 //this will give the row to be highlihted
  var row = parseInt(clickeddata/x);
  //current color calculation
  currentColor = currentColor == "rgb(255, 255, 255)" ? "rgb(255, 0, 255)" : "rgb(255, 255, 255)";
  //iterate through all the rectangle
  d3.selectAll("rect")[0].forEach(function(r){
    //all rectangle with same row 
    if(parseInt(d3.select(r).data()/x) == row){
      //make it color as it is in the same row
      d3.select(r)
        .attr("clicked", true)
        .transition()
          .style("fill", currentColor);     
    }
  });

此处为工作代码。