D3.JS鼠标悬停时如何计算某个属性的圆圈数

D3.JS how to count number of circles of a certain attribute on mouseover

本文关键字:属性 计算 悬停 鼠标 JS 何计算 D3      更新时间:2023-09-26

假设我在 D3 中制作了几个圆圈,并且都采用此鼠标悬停功能......

.on("mouseover", function(d) {
    //I get the co attribute of the one being hovered
    var theCompany = d3.select(this).attr("co"); 
    //and then I style all of the circles with that same co attribute       
    d3.selectAll("circle.circle[co='"+theCompany+"']").attr("stroke", "#999"); 
}

在这个鼠标悬停功能中,有没有办法计算我悬停在上面带有"co"属性的圆圈数?

可以使用内置

的方法size d3.js来获取所选项的计数。

var count = d3.selectAll("circle.circle[co='"+theCompany+"']").size()

此外(这可能在前面的函数中派上用场)还有一种方法可以检查选择是否为空。

d3.select('<selector'>).empty()这将根据您的选择是否有任何结果返回true/false