[英]Function filter not working as expected in d3js
我有这个 HTML 结构
<g class="type type-project" id="g-nsmart_city_lab" transform="translate(954.9537424482861,460.65694411587845)">
<circle class="highlighter-circles" fill-opacity="0" r="70" fill="rgb(150,150,150)" id="hc-nsmart_city_lab"></circle>
<circle class="node" r="50" fill="#768b83" id="nsmart_city_lab" filter="url(#blur)"></circle>
<text font-family="Comic Sans MS" font-size="18px" fill="black" class="nodetext" id="t-nsmart_city_lab" style="text-anchor: middle;" x="0" y="0">SMART CITY LAB</text>
<image href="./icons/project.svg" width="30" height="30" id="i-nsmart_city_lab" class="nodeimg"></image>
<image href="./icons/expand2.svg" width="30" height="30" for-node="nsmart_city_lab" x="25" y="-45" id="ne-nsmart_city_lab" class="nodeexp" style="visibility: hidden;" data-expandable="false"></image>
<circle class="inv_node" r="50" fill="red" fill-opacity="0" id="inv_nsmart_city_lab"></circle>
</g>
我想对满足特定条件的g
元素进行处理。 但是做的时候,
d3.selectAll("g.type").filter(g_element => g_element.class !== "whatever");
过滤器没有按预期工作(至少对我而言)。 g_element.class
是undefined
。 调试后,由于某种原因过滤返回<circle class="node" r="50" fill="#768b83" id="nsmart_city_lab" filter="url(#blur)"></circle>
而不是 a g
对象访问其属性并进行过滤。
这怎么能做到呢?
在这里你有一个 jsfiddle,它总是返回未定义, https ://jsfiddle.net/k6Ldxtof/40/
在你的片段...
d3.selectAll("g.type").filter(g_element => g_element.class !== "whatever");
...您命名为g_element
的第一个参数是绑定到该元素的数据。 由于这里没有数据绑定,这显然是undefined
。
要获取元素,您必须使用this
。 但是,由于您在这里使用了箭头函数,因此您需要结合使用第二个和第三个参数:
d3.selectAll("g.type")
.filter((_,i,n) => console.log(n[i]))
然后要获得课程,您只需使用吸气剂...
d3.selectAll("g.type")
.filter((_,i,n) => console.log(d3.select(n[i]).attr("class")))
或者,甚至更简单,使用classList
:
d3.selectAll("g.type")
.filter((_, i, n) => console.log(n[i].classList))
这是演示:
function create() { let g = d3.select("body") .append("svg") .attr("height", "500") .attr("width", "500") .append("g"); g.append("g") .attr("class", "type type-red") .attr("data-color", "red") .append("circle") .attr("r", 50) .attr("fill", "red") .attr("cx", 50) .attr("cy", 50); g.append("g") .attr("class", "type type-green") .attr("data-color", "green") .append("circle") .attr("r", 50) .attr("fill", "green") .attr("cx", 200) .attr("cy", 50); g.append("g") .attr("class", "type type-blue") .attr("data-color", "blue") .append("circle") .attr("r", 50) .attr("fill", "blue") .attr("cx", 100) .attr("cy", 150); filter_out(); } /***************** USING THE SELECTOR ********************/ function filter_out() { d3.selectAll("g.type") .filter((_, i, n) => console.log(n[i].classList)) .attr("opacity", 0.5); } create();
<script src="https://d3js.org/d3.v4.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.