我必须选择具有特定 transform
的 SVG 元素属性,只知道其中的一部分。让我用一个例子更好地解释。
这些是我要选择的元素:
<g transform='matrix(96, 0, 0, -96, 217.04, 43.052)'></g>
<g transform='matrix(96, 0, 0, -96, 317.04 53.052)'></g>
<g transform='matrix(96, 0, 0, -96, 417.04, 63.052)'></g>
<g transform='matrix(96, 0, 0, -96, 517.04, 73.052)'></g>
<g transform='matrix(96, 0, 0, -96, 617.04, 83.052)'></g>
我想将它们全部选中并且(最初)使用类似下面的代码听起来是个好主意:
d3.selectAll("g").filter("[transform='matrix(96, 0, 0, -96)]'");
问题是,显然,选择返回为空,我想知道如何告诉 d3 只选择那些 <g>
匹配 transform 属性的前 4 个参数的元素。
最佳答案
您可以在一个选择器中组合 g
的初始选择和过滤:
d3.selectAll("g[transform^='matrix(96, 0, 0, -96']");
注意 attribute selector 中 ^=
的使用:
[attr^=value]
Represents an element with an attribute name of attr the value of which is prefixed by "value".
工作演示:
var filtered = d3.selectAll("g[transform^='matrix(96, 0, 0, -96']");
console.log(filtered.size()); // 3: The first three groups
<script src="https://d3js.org/d3.v4.js"></script>
<svg>
<g transform="matrix(96, 0, 0, -96, 217.04, 43.052)"></g>
<g transform="matrix(96, 0, 0, -96, 317.04 53.052)"></g>
<g transform="matrix(96, 0, 0, -96, 417.04, 63.052)"></g>
<g transform="matrix(10, 0, 0, -96, 517.04, 73.052)"></g> <!--different transform-->
<g transform="matrix(20, 0, 0, -96, 617.04, 83.052)"></g> <!--different transform-->
</svg>
当然,你也可以从分组的选择中拆分过滤:
d3.selectAll("g").filter("[transform^='matrix(96, 0, 0, -96']");
或者,为了更好地控制过滤,您可以为 selection.filter()
提供过滤函数。从而访问所选元素以及绑定(bind)到它们的数据。
d3.selectAll("g")
.filter(function(d, i, nodes) { // Most versatile approach
return d3.select(this)
.attr("transform")
.startsWith("matrix(96, 0, 0, -96");
// .lastIndexOf("matrix(96, 0, 0, -96", 0); // For those on IE
});
虽然所有这些解决方案都会产生相同的结果,但适合您问题的解决方案可能是性能、简单性和多功能性之间的权衡。
关于javascript - D3.js - 选择知道属性的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43684234/