Javascript 当我删除一个矩形时,我怎么能同时删除它的字母呢

Javascript 当我删除一个矩形时,我怎么能同时删除它的字母呢,javascript,csv,d3.js,svg,Javascript,Csv,D3.js,Svg,我试图删除一些超出边界的矩形,但当我删除它们时,我无法删除它们的字母。有人能解释一下我做错了什么吗?我还希望我的矩形具有不透明度,但是当我插入这行代码.attr(“类”,函数(d){if((d.x+d.width)>width | |(d.y+d.height)>height)时,返回“delete”})它们失去了不透明度。我正在从csv文件中读取所有(x、y、宽度、高度等)。我的代码是: `<!DOCTYPE html> <meta charset="utf-8">

我试图删除一些超出边界的矩形,但当我删除它们时,我无法删除它们的字母。有人能解释一下我做错了什么吗?我还希望我的矩形具有不透明度,但是当我插入这行代码
.attr(“类”,函数(d){if((d.x+d.width)>width | |(d.y+d.height)>height)时,返回“delete”})它们失去了不透明度。我正在从csv文件中读取所有(x、y、宽度、高度等)。我的代码是:

 `<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */

.rect { fill-opacity:.50; stroke: rgb(60,100,200); stroke-width:1px;}

</style>
<body>

<!-- load the d3.js library -->     
<script src="//d3js.org/d3.v4.min.js"></script>
<script>

// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 1024,
    height = 768;

    // width = 1074 - margin.left - margin.right,
    // height = 818 - margin.top - margin.bottom;

// set the ranges
var x = d3.scaleLinear()
      .range([0, width]);
var y = d3.scaleLinear()
      .range([height, 0]);

  //     x.domain([0, d3.max(data, function(d) { return d.x + d.width  })]);
  // y.domain([0, d3.max(data, function(d) { return d.y + d.height  })]);

x.domain([0, width]);
y.domain([0, height]);
// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
 .append("g")
  .attr("transform", 
      "translate(" + margin.left + "," + margin.top + ")");

// get the data
  d3.csv("rectangles.csv", function(error, data) {

    if (error) throw error;

    data.forEach(function(d){
      d.height = +d.height;
      d.width = +d.width;
      d.x = +d.x;
      d.y = +d.y;
    });



  svg.selectAll(".rect")
    .data(data)
  .enter().append("rect")
   .attr("class", "rect")
   .attr("x", function(d) { return x(d.x); })
   .attr("y", function(d) { return  y(d.y) - (height - y(d.height)) })
   .attr("width", function(d) { return x(d.width) })
   .attr("height", function(d) { return height - y(d.height) })
   .attr("fill", function(d) {return d.color})

   .attr("class", function(d){if((d.x + d.width)> width || (d.y + d.height)> height) return "delete"});
   // .attr("class", function(d){if(d.x>0 && d.x < 1024 - d.width && d.y > 0 && d.y < 768 - d.height) return "delete"})

   svg.selectAll("rect.delete").remove();


  svg.selectAll("text")
    .data(data)
  .enter().append("text")
    .attr("fill","red")
    .attr("y", function(d) { return y(d.y) - (height - y(d.height))/20; })
    .attr("x", function(d) { return x(d.x) + x(d.width)/10; })
    .style("text-anchor", "middle")
    .text(function(d) {console.log(d); return d.txt});

 // add the x Axis
 svg.append("g")
  .attr("transform", "translate(0," + height + ")")
  .call(d3.axisBottom(x));

 // add the y Axis
 svg.append("g")
  .call(d3.axisLeft(y));
});
 </script>
</body>`
`
/*设置CSS*/
.rect{填充不透明度:.50;笔划:rgb(60100200);笔划宽度:1px;}
//设置图形的尺寸和边距
var margin={顶部:20,右侧:20,底部:30,左侧:40},
宽度=1024,
高度=768;
//宽度=1074-margin.left-margin.right,
//高度=818-margin.top-margin.bottom;
//设定范围
var x=d3.scaleLinear()
.范围([0,宽度]);
变量y=d3.scaleLinear()
.范围([高度,0]);
//域([0,d3.max(数据,函数(d){返回d.x+d.width}));
//域([0,d3.max(数据,函数(d){返回d.y+d.height})];
x、 域([0,宽度]);
y、 域([0,高度]);
//将svg对象附加到页面主体
//将“组”元素附加到“svg”
//将“组”元素移动到左上角
var svg=d3.选择(“正文”).追加(“svg”)
.attr(“宽度”,宽度+边距。左侧+边距。右侧)
.attr(“高度”,高度+边距。顶部+边距。底部)
.附加(“g”)
.attr(“转换”,
“翻译(“+margin.left+”,“+margin.top+”);
//获取数据
d3.csv(“rectangles.csv”),函数(错误,数据){
如果(错误)抛出错误;
data.forEach(函数(d){
d、 高度=+d.高度;
d、 宽度=+d.宽度;
d、 x=+d.x;
d、 y=+d.y;
});
svg.selectAll(“.rect”)
.数据(数据)
.enter().append(“rect”)
.attr(“类”、“rect”)
.attr(“x”,函数(d){返回x(d.x);})
.attr(“y”,函数(d){返回y(d.y)-(高度-y(d.height))}
.attr(“宽度”,函数(d){返回x(d.width)})
.attr(“高度”,函数(d){返回高度-y(d.height)})
.attr(“fill”,函数(d){return d.color})
.attr(“类”,函数(d){if((d.x+d.width)>width | |(d.y+d.height)>height)返回“delete”});
//.attr(“类”,函数(d){if(d.x>0&&d.x<1024-d.width&&d.y>0&&d.y<768-d.height)返回“delete”})
selectAll(“rect.delete”).remove();
svg.selectAll(“文本”)
.数据(数据)
.enter().append(“文本”)
.attr(“填充”、“红色”)
.attr(“y”,函数(d){返回y(d.y)-(高度-y(d.height))/20;})
.attr(“x”,函数(d){返回x(d.x)+x(d.width)/10;})
.style(“文本锚定”、“中间”)
.text(函数(d){console.log(d);返回d.txt});
//添加x轴
svg.append(“g”)
.attr(“变换”、“平移(0)”、“高度+”)
.call(d3.axisBottom(x));
//添加y轴
svg.append(“g”)
.调用(d3.左(y));
});
`

对于您来说,更简单的方法是先过滤掉数据,而不是先渲染矩形,然后删除它们。您遇到的问题是,尽管文本和矩形使用相同的数据,但它们之间并没有真正的链接。正如@rioV8所指出的,正确的方法是使用
g
元素将相关项目分组在一起

我也希望我的矩形有不透明度,但是当我插入这行代码时,attr(“类”,函数(d){if((d.x+d.width)>width | |(d.y+d.height)>height)返回“delete”});他们失去了透明度

之所以会发生这种情况,是因为
attr
覆盖了以前的值,并且由于您返回了“delete”或“undefined”,因此它不再具有“rect”类。使用类时,不要使用
attr
而使用
classed
,例如

.classed('delete', function(d){
    if (shouldBeDeleted) return true;
    return false; 
})
通过这种方式,您可以只切换
delete
class,并保留元素的任何其他类

这里演示了如何过滤数据,以及如何将相关的矩形和标签分组到
g
元素中

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
    svg { margin-left: auto; margin-right: auto; border: solid 1px; }
    g.item rect {
      fill-opacity: 0.2;
    }
  </style>
</head>

<body>
  <script>


    var data = [{
        x: -50,
      y: 150,
      width: 100,
      height: 100,
      text: 'A',
      color: '#f00'
    }, {
      x: 100,
      y: 150,
      width: 100,
      height: 100,
      text: 'B',
      color: '#0f0'
    }, {
      x: 350,
      y: 150,
      width: 100,
      height: 100,
      text: 'C',
      color: '#00f'
    }];

    var width = 400,
        height = 400;

    var svg = d3.select("body").append("svg")
      .attr("width", width)
      .attr("height", height);

    var items = svg.selectAll('g.item')
        .data(data.filter(function(i){
            return i.x > 0 && i.x + i.width < width && i.y > 0 && i.y + i.height < height;
      }));

    items = items.enter()
        .append('g')
        .classed('item', true)
        .merge(items)
        .attr('transform', function(d){
        return "translate("+d.x +"," +d.y+")";
        });

    items.append('rect')
        .attr('width', (d) => d.width)
        .attr('height', (d) => d.height)
        .style('fill', (d) => d.color);

    items.append('text')
        .text((d) => d.text);

  </script>
</body>

正文{边距:0;位置:固定;顶部:0;右侧:0;底部:0;左侧:0;}
svg{左边距:自动;右边距:自动;边框:实心1px;}
g、 项矩形{
填充不透明度:0.2;
}
风险值数据=[{
x:-50,
y:150,
宽度:100,
身高:100,
正文:“A”,
颜色:'#f00'
}, {
x:100,
y:150,
宽度:100,
身高:100,
正文:“B”,
颜色:'#0f0'
}, {
x:350,
y:150,
宽度:100,
身高:100,
文本:“C”,
颜色:'#00f'
}];
可变宽度=400,
高度=400;
var svg=d3.选择(“正文”).追加(“svg”)
.attr(“宽度”,宽度)
.attr(“高度”,高度);
var items=svg.selectAll('g.item')
.数据(数据过滤器(功能i){
返回i.x>0&&i.x+i.width0&&i.y+i.heightd.width)
.attr('height',(d)=>d.height)
.style('fill',(d)=>d.color);
items.append('text')
.text((d)=>d.text);

将rect和文本添加到每个rect的一个单独的
g
元素中,如果您希望删除
rect
,请删除
g
。非常感谢@riov8非常感谢您帮助我了解它的工作原理。