d3.js:获取td值

问题描述 投票:0回答:1

我是d3.js的新手我面临的问题是我不确定如何获取td的值。

html

<table class="table">
<thead><tr>
    <th>S No</th>
    <th>Name</th>
    <th>Credit</th>
</tr>
</thead>
<tbody>
<tr>
    <td>2</td>
    <td>Arun</td>
    <td>Positive</td>
</tr>
<tr>
    <td>3</td>
    <td>Mickey</td>
    <td>Negetive</td>
</tr>
<tr>
    <td>4</td>
    <td>Zack</td>
    <td>Positive</td>
</tr>
</tbody>

我阅读了d3.js上的文档,但找不到有关如何从表中检索数据的文档。假设我想在Credit上附加具有背景颜色(绿色)的div,该值具有negetive的值,我们如何实现这一目标

这是我尝试过的

let selection = d3.selectAll("tr")
console.log("Get Table " + selection)

let headerElement = selection.nodes()[0];
let output = selection.selectAll("td")

我试图用console.log(输出[“ 0”] [1])打印第th行的值但我正在接收错误。

提前谢谢您

javascript d3.js dom
1个回答
1
投票

由于D3 v4选择是对象,而不是数组,因此您不能像在output["0"][1]中那样对待它们。

循环选择的惯用方法是使用selection.each。例如:

const tds = d3.selectAll("td")
  .each(function() {
    console.log(d3.select(this).text());
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th>S No</th>
      <th>Name</th>
      <th>Credit</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2</td>
      <td>Arun</td>
      <td>Positive</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Mickey</td>
      <td>Negetive</td>
    </tr>
    <tr>
      <td>4</td>
      <td>Zack</td>
      <td>Positive</td>
    </tr>
  </tbody>

如果您不想进行其他选择,则d3.select(this).text()this.innerHTML相同。

因此,您可以使用相同的each设置“信用值具有消极价值的信用底色(绿色)]],如您所说:

const tds = d3.selectAll("td")
  .each(function() {
    d3.select(this).style("background-color", this.innerHTML === "Positive" ? "green" : null)
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th>S No</th>
      <th>Name</th>
      <th>Credit</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>2</td>
      <td>Arun</td>
      <td>Positive</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Mickey</td>
      <td>Negetive</td>
    </tr>
    <tr>
      <td>4</td>
      <td>Zack</td>
      <td>Positive</td>
    </tr>
  </tbody>
© www.soinside.com 2019 - 2024. All rights reserved.