gpt4 book ai didi

javascript - d3.js - 使用 .selectAll() 根据属性值选择 Node 元素

转载 作者:行者123 更新时间:2023-11-29 20:29:20 30 4
gpt4 key购买 nike

我有一个像这样的 Node :

<div>
<svg ...>
<g class="graph">
<path class="myarea" d="...AAA..." pos="p1"> </path>
</g>
<g class="graph">
<path class="myarea" d="...BBB..." pos="p2"> </path>
</g>
<g class="graph">
<path class="myarea" d="...CCC..." pos="p3"> </path>
</g>
/svg>
</div>

我正在尝试选择具有属性 pos='p2' 的特定 Node (例如 where d="...BBB...")/p>

d3.selectAll(".myarea").each(function(d,i) {
console.log("-> ", d3.select(this).attr("pos"), d3.select(this).attr("pos") == 'p2' );

});

这会产生/返回一个包含所有 3 个条目的数组:

-> p0 false

-> p1 true

-> p2 false

-> [Array(3)]

我只想选择一个,在本例中是带有 .attr("pos") == 'p2' 的那个,所以我只想返回一个元素。

我试过 map()filter() 但没有成功。

根据属性值选择特定元素的正确方法是什么?

最佳答案

Selection.filter()

可以根据类别选择一堆元素,然后使用selection.filter() 过滤选择:

svg.selectAll("whatever")
.filter(function() {
return d3.select(this).attr("col") == 2; // filter by single attribute
})

var svg = d3.select("svg");

svg.selectAll("rect")
.filter(function() {
return d3.select(this).attr("col") == 2
})
.attr("fill","orange");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect width="20" height="20" x="5" y="5" col="1" row="1"></rect>
<rect width="20" height="20" x="30" y="5" col="2" row="1" ></rect>
<rect width="20" height="20" x="5" y="30" col="1" row="2" ></rect>
<rect width="20" height="20" x="30" y="30" col="2" row="2" ></rect>
</svg>

使用 CSS 选择器按属性值选择

但是,我们可以使用描述的 CSS 选择器一步完成所有操作,而不是选择一堆元素然后过滤选择 here .这让我们可以选择元素的属性等于特定值:

svg.selectAll("rect[col='2']")

var svg = d3.select("svg");

svg.selectAll("rect[col='2']")
.attr("fill","orange");

d3.selectAll("rect[col='1'][row='1']")
.attr("fill","steelblue");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<rect width="20" height="20" x="5" y="5" col="1" row="1"></rect>
<rect width="20" height="20" x="30" y="5" col="2" row="1" ></rect>
<rect width="20" height="20" x="5" y="30" col="1" row="2" ></rect>
<rect width="20" height="20" x="30" y="30" col="2" row="2" ></rect>
</svg>

在上面我还使用了:

d3.selectAll("rect[col='1'][row='1']") to select based on two attribute values.

你也可以用一个类而不是一个通用标签来代替查找,所以对你来说这可能看起来像:

d3.selectAll(".myarea[d='BBB'][pos='p2']")

关于javascript - d3.js - 使用 .selectAll() 根据属性值选择 Node 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58701387/

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