gpt4 book ai didi

javascript - 使用 D3.js 迭代 SVG 元素

转载 作者:行者123 更新时间:2023-12-02 15:41:19 26 4
gpt4 key购买 nike

我想做的事情相对简单,但我对 JS 和 D3.js 很陌生。我通过 D3.js 使用 SVG 创建了一堆矩形。

我添加了一些代码来处理单击事件,在其中我想迭代所有绘制的节点,并使用它们执行某些操作,只要特定属性与已单击的属性中的相同属性匹配即可。

这是绘制矩形的代码(这里只有一个);

d3.select("svg")
.append("rect").attr("x", 50)
.attr("y", 10)
.attr("height", 20)
.attr("width", 200)
.attr("title", "catalog")
.style("fill", "#CB4B19")
.on("click", mouseClick)

以下是我尝试检索绘制的每个矩形的“标题”属性并将其与单击的矩形进行比较的方法(在本例中,只需将其记录在控制台中)。我知道这可能是基本的,但我不知道我在这里做错了什么。

function mouseClick(d) {

var t = d3.select(this).attr("title"); //store the "title" property of the clicked rectangle

d3.selectAll("rect").each(function(d, i){ //Select all rectangles drawn
if(d3.select(this).attr("title") == t){ //for each one, if the "title" property = the one initially chosen
console.log(t); //do something here
}
})
}

最佳答案

您的代码实际上似乎工作正常。至少对我来说是这样。我要说的一件事是 d3 确实模仿了 jQuery 语法,因为它允许您使用 d3.select('element[attributeName="?"]') 语法选择具有属性的元素。您可以阅读更多关于 selections here .

所以对于你的例子,你可以这样做

var t = d3.select(this).attr("title"); 

// select all rectangles with the attribute title
d3.selectAll("rect[title='" + t + "']").each(function(d, i){
console.log(t);
});

您不再需要 if 语句进行检查,因为您只需选择它们。我做了一个简单的 jsFiddle 来展示这一点。我制作了 3 种不同类型的矩形,它们具有不同的 title 属性,当您单击它们时,它只会选择具有相同 title 属性的 rect

http://jsfiddle.net/augburto/znqe8nqr/

关于javascript - 使用 D3.js 迭代 SVG 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544500/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com