table.innerHTML = " " ;无法正确清除 HTML 表格



当前,我在选择一个键(例如European Countries(和值(例如CCD-2(后,使用JavaScript创建一个表,Population调用API,然后返回前端,输出一个表:

Countries:   Population:
France                67
Germany               83
UK                    66

当我选择一个新值,例如GDP时,它会很好地清除表,并再次正确地重新渲染它,如下所示:

Countries:           GDP:
France                2.7
Germany               3.8
UK                    2.8

但是,如果我选择了一个新的密钥Asian Countries,则会在现有的密钥后面附加一个新表:

Countries:           GDP:
France                2.7
Germany               3.8
UK                    2.8
China                14.3
Japan                 5.0

这是JavaScript:

1  renderTable() {
2      var tbody = document.getElementById('tbody');
3      tbody.innerHTML = "";
4      var obj = this.state;
5      for (let [key, value] of Object.entries(obj)) {
6          var tr = "<tr>";
7          tr += `<td>${key}</td><td>${value.toString()}</td></tr>`;
8          tbody.innerHTML += tr;
9      }
10  }

以及表呈现之前的HTML:

1 <table>
2     <tbody id="tbody"></tbody>
3 <table>

因此,目前,当选择新的时,会删除该表并创建一个新表,但当选择新后,只会附加一个新的表。无论我选择的是新的键还是值,如何确保每次都清除表,然后重新渲染?

编辑:

this.state是一个以国家名称为密钥的对象,它看起来如下:

France: 67
Germany: 83
UK: 66
...

";"选择";来自两个Form.Groups

<Form.Group>
<Form.Label>Continent</Form.Label>
<Form.Control as="select" multiple id="select-continent"> 
<option value="asia">Asia</option>
<option value="europe">Europe</option>
</Form.Control>
</Form.Group>
<Form.Group>
<Form.Label>Attribute</Form.Label>
<Form.Control as="select" multiple id="select-attribute"> 
<option value="Population">Country Population (millions)</option>
<option value="GDP">GDP (USD) </option>
</Form.Control>
</Form.Group>
<Button variant="success" onClick={() => this.callAPI(document.getElementById('select-continent').value, document.getElementById('select-attribute').value)}>
Search
</Button>

其中callAPI()如下并且componentDidUpdate检测this.state的变化:

callAPI( continent, attribute ) {
var h = new Headers();
h.append("Content-Type", "application/json");
h.append("Access-Control-Allow-Origin", "*");
var raw = JSON.stringify({"continent":continent, "attribute":attribute});
var requestOptions = {
method: 'POST',
headers: h,
body: raw,
redirect: 'follow'
};
fetch('/api/continents-countries', requestOptions).then(res => res.json()).then(data => {
this.setState(data)
});
}
componentDidUpdate(prevProps) {
if (prevProps.state !== this.state) {
this.renderTable();
}
}

使用<tbody>元素的[index]而不是id。

function renderTable() {
var tbody = document.getElementById("myTable").tBodies[0];
tbody.innerHTML = '';
}
<style>table, td {border: 1px solid black;}</style>
<table id="myTable">
<tbody>
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
</tbody>
<tbody>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</tbody>
</table>
<p><button onclick="renderTable()">Erase tbody</button>

最新更新