javascript - 如何选择 d3 中具有特定属性值的元素

标签 javascript d3.js

我正在浏览器上使用 d3 绘制项目。我想根据它们的属性来强调其中的一些。例如,我有杂货、肥皂,其中肥皂元素的类型为 [for_bath (OR) for_cloth_wash]。我想在所有肥皂和杂货中选择特定于 for_bath 的元素,并在同一屏幕上组合并绘制在一起。

如何?

另外,我的另一个疑问是 document.getElementById() 在 d3 的选择代码中不起作用。我是真的还是疏忽了?

编辑

var data = {"soaps":{"lux":"bath", "cinthol":"bath", "rin","cloth_washing"}, 
            "shoes":{"valentine":"teens", "bootie":"kids", "kuuch":"kids"}};

//  Now I want to show all bath soaps highlighted, may be with a circle around them.
var svg = d3.select("svg")
            .selectAll(".items")
            .data(data).enter()
            .append("circle")
            //  highlighting styles
;

在这里,我想选择沐浴皂并将其四舍五入。

最佳答案

您还没有给我们任何代码,所以我将在这里猜测。您可能正在寻找的是 CSS attribute selectors 。因此,如果您想选择将属性 soap 设置为 for_bath 的元素,您可以这样做

d3.selectAll("[soap=for_bath]");

这仅适用于 DOM 元素。如果您正在谈论数据元素,那么您可以使用 .filter() method :

data.filter(function(d) { return d.soap == "for_bath"; });

关于你的第二个问题,我不明白你的意思。 d3.select()d3.selectAll() 的参数是 DOM 选择器,因此 document.getElementById() 没有意义这里。不过,您当然可以使用它的其他功能:

d3.selectAll("something").each(function() {
  d3.select(this); // the current element
  document.getElementById("something"); // another element
});

关于javascript - 如何选择 d3 中具有特定属性值的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273097/

相关文章:

javascript - 如何将plotly.js应用到现有的svg组<g>作为目标而不是应用到目标<div>元素?

javascript - d3.slider 和在时间轴上过滤的日期

通过 HTML 元素加载 Javascript 幻灯片图像

javascript - 将链接附加到整个 HTML5 Canvas

javascript - RNFetchBlob - 无法在生成的图像文件中获取 API 数据

javascript - 用 d3 制作日历

javascript - D3重新出现后圈太大

javascript - JS 拆分变量

javascript - 单选按钮 : weird selection behaviour

javascript - 使用 setTimeout 延迟 d3 转换