【问题标题】:d3.js - Select node element based on attributes value using .selectAll()d3.js - 使用 .selectAll() 根据属性值选择节点元素
【发布时间】:2020-03-01 05:44:42
【问题描述】:

我有一个类似的节点:

<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' 属性的特定节点(例如 where d="...BBB..."

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

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

-> p0 错误

-> p1 真

-> p2 错误

-> [数组(3)]

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

我尝试过使用map()filter(),但没有成功。

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

【问题讨论】:

  • 能不能不用d3.selectAll(".myarea[d='BBB'][pos='p2']")之类的,D3支持任何有效的css选择器,比如this(匹配单个属性)和this(匹配多个属性)
  • 很好,这行得通。不知道那个语法.select(.myarea[pos='p2']")

标签: javascript node.js d3.js filter


【解决方案1】:

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 选择器按属性值选择

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

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']")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多