选择除特定数据集之外的所有内容

时间:2016-11-25 06:53:12

标签: javascript select d3.js mouseover selectall

我需要选择除了我悬停在的数据集之外的所有内容,到目前为止我已经拥有它所以this未被选中但现在我需要使其this以及具有公共数据集的所有内容未被选中

.on("mouseover", function(d) {
    console.log(d);
    var circleUnderMouse = this;
    d3.selectAll(".dot").filter(function(d,i) {
        return (this !== circleUnderMouse);
    })
})

1 个答案:

答案 0 :(得分:0)

您可以只使用this参数。

,而不是使用datum

将鼠标悬停在某个节点上时...

  

将为每个选定元素计算指定的侦听器,传递当前数据(d),当前索引(i)和当前组(节点),并将其作为当前DOM元素。

因此,要查找具有相同数据的所有其他元素,您只能使用第一个参数,其中包含 datum ,而不是 this ,这是DOM元素

这是一个向您展示的演示。我们有一个包含位置的数据集和一个名为type的键:

var data = [{type: "foo", x: 30, y: 90},
    {type: "foo", x: 10, y: 50},
    //etc...
];

将鼠标悬停在一个圆圈上,我们会选择所有其他不与type属性共享相同值的圆圈,让它们消失:

circles.on("mouseover", function(d) {
    var filtered = circles.filter(function(e) {
        return e.type != d.type
    });
    filtered.attr("opacity", 0);
})

以下是演示:

var svg = d3.select("svg");
var data = [{
    type: "foo",
    x: 30,
    y: 90
}, {
    type: "foo",
    x: 10,
    y: 50
}, {
    type: "foo",
    x: 220,
    y: 130
}, {
    type: "baz",
    x: 40,
    y: 40
}, {
    type: "bar",
    x: 170,
    y: 20
}, {
    type: "baz",
    x: 220,
    y: 110
}, {
    type: "bar",
    x: 130,
    y: 120
}, {
    type: "foo",
    x: 150,
    y: 50
}, {
    type: "baz",
    x: 30,
    y: 110
}, {
    type: "foo",
    x: 100,
    y: 220
}];

var color = d3.scaleOrdinal()
    .domain(["foo", "bar", "baz"])
    .range(["teal", "brown", "gold"]);

var circles = svg.selectAll(".circles")
    .data(data)
    .enter()
    .append("circle")
    .attr("cx", d => d.x)
    .attr("cy", d => d.y)
    .attr("r", 8)
    .attr("fill", d => color(d.type));

circles.on("mouseover", function(d) {
    var filtered = circles.filter(function(e) {
        return e.type != d.type
    });
    filtered.attr("opacity", 0);
}).on("mouseout", function() {
    circles.attr("opacity", 1)
})
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>