【问题标题】:d3.js selectAll method does not select all elements?d3.js selectAll 方法不选择所有元素?
【发布时间】:2021-05-26 15:11:55
【问题描述】:

我是 d3.js 的新手。文档告诉我.selectAll“选择与指定选择器字符串匹配的所有元素”。但是当我尝试使用d3.selectAll("p").selectAll("b")在下面的html代码中获取所有b元素时,最后一个b元素没有被选中:

<p>
    <b>selected</b>
    <b>selected</b>
    <h4>some word</h4>
    <b>not selected</b>
</p>

有人可以指导我吗?谢谢!

var selection = d3.selectAll("p").selectAll("b");

console.log("b elements selected: ", selection.size());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<p>
        <b>selected</b>
        <b>selected</b>
        <h4>some word</h4>
        <b>not selected</b>
    </p>

【问题讨论】:

  • 没错,新的,你选择所有的 p 然后所有的 b 在他们每个人里面。尝试select(p).selectAll(b) 将选择第一个 p 和其中的所有 b
  • @somallg 谢谢,但我已经尝试过select(p).selectAll(b) 并且仍然没有选择最后一个 b 元素...

标签: javascript html d3.js


【解决方案1】:

p 元素不能包含 h4 元素。一个p 只能包含phrasing content,例如一个b 元素。在您的情况下,h4 标签关闭了p

如果紧跟

元素,则可以省略结束标记 通过 ...

, ... (source)

所以你的第三个b 根本不在p 中。这就是为什么您不能选择它作为p 的子项。您可以尝试两个 p 元素,h4 介于两者之间,或者您可以使用具有适当样式的 span

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<p>
    <b>selected</b>
    <b>selected</b>
</p>
    <h4>some word</h4>
<p>
    <b>not selected</b>
</p>

<script>
var selection = d3.selectAll("p").selectAll("b");

console.log(selection.size());


</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<p>
    <b>selected</b>
    <b>selected</b>
    <span>some word</span>
    <b>not selected</b>
</p>

<script>
var selection = d3.selectAll("p").selectAll("b");

// for demonstration as all `b` elements are in the first `p` element.
var selection2 = d3.select("p").selectAll("b");


console.log(selection.size());
console.log(selection2.size());


</script>

【讨论】:

  • 谢谢!!从来没有想过html元素的规则。
猜你喜欢
  • 2020-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-19
  • 2020-12-12
相关资源
最近更新 更多