简体   繁体   English

从选择中排除元素

[英]Exclude an element from a selection

Which is the most straightforward way to exclude an item (or maybe two or few) from a selection? 从选择中排除一个项目(或两个或几个)的最直接方法是什么?

For example, in the following code ( JSFiddle snippet ) I want to change the y-position for all squares except the third one. 例如,在下面的代码( JSFiddle snippet )中,我想更改除第三个正方形以外的所有正方形的y位置。 What have I to do? 我该怎么办

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

for (var i=0;i<10;i++) {
svg.append("rect")
  .attr({
    x: 32*i,
    y: 0,
    height: 30,
    width: 30,
    fill: "green"
  })
} 

var rects=d3.selectAll("rect"); // this line has to be changed/completed to exclude the third rect

rects.forEach(function(rect, i){
    d3.select(rect).attr("y", 20)
})

PS: The forEach function contains an error since the instruction is not executed, but I'm not able to find my mistake. PS:因为未执行指令,所以forEach函数包含错误,但是我找不到我的错误。

For de d3 framework you could use the selection.filter(selector) . 对于d3框架,您可以使用selection.filter(selector) Using the filter function, you provide a function that returns false for the elements you want to filter. 使用filter函数,您提供了一个函数,该函数为要过滤的元素返回false Documentation: https://github.com/mbostock/d3/wiki/Selections#filter 文档: https : //github.com/mbostock/d3/wiki/Selections#filter

And for the 'PS', there's no forEach on d3, you must use the each function. 对于“ PS”,d3上没有forEach,您必须使用each函数。

Code below should work. 下面的代码应该工作。

var rects = d3.selectAll("rect").filter(function(d, i) { return i != 2; });

rects.each(function(d, i){
        d3.select(this).attr("y", 20);
})

Inside your forEach, you have access to 'i' which is the index. 在forEach内部,您可以访问索引的“ i”。 Since the third item is equal to an index of 2 (due to it being 0-based), you can simply add an if statement. 由于第三项等于2的索引(由于它从0开始),因此您可以简单地添加if语句。

rects.forEach(function(rect, i){
    if (i !== 2) {
        d3.select(rect).attr('y', 20);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM