[英]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.