js实现列表框选项改变时隐藏或显示不同表格
时间: 2024-01-20 22:04:36 浏览: 27
你可以使用JavaScript来实现这个功能。首先,你需要获取到多个表格元素的引用。然后,你可以给列表框添加一个事件监听器,当选项改变时,触发一个函数来隐藏或显示不同的表格。
以下是一个基本的示例代码:
HTML代码:
```html
<select id="select-box">
<option value="table1">显示表格1</option>
<option value="table2">显示表格2</option>
</select>
<table id="table1" class="table">
<thead>
<tr>
<th>表头 1</th>
<th>表头 2</th>
<th>表头 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容 1</td>
<td>内容 2</td>
<td>内容 3</td>
</tr>
</tbody>
</table>
<table id="table2" class="table">
<thead>
<tr>
<th>表头 1</th>
<th>表头 2</th>
<th>表头 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>内容 1</td>
<td>内容 2</td>
<td>内容 3</td>
</tr>
</tbody>
</table>
```
CSS代码:
```css
.table {
display: none;
}
```
JavaScript代码:
```javascript
const selectBox = document.getElementById('select-box');
const tables = document.querySelectorAll('.table');
selectBox.addEventListener('change', function() {
tables.forEach(function(table) {
if (table.id === selectBox.value) {
table.style.display = 'table';
} else {
table.style.display = 'none';
}
});
});
```
这个代码片段中,我们首先获取了`select`元素和所有的表格元素的引用,然后给`select`元素添加了一个`change`事件监听器。当`select`元素的值改变时,我们遍历所有的表格元素,如果当前表格元素的`id`等于`select`元素的值,我们将其`display`属性设置为`table`,显示该表格;否则,我们将其`display`属性设置为`none`,隐藏该表格。通过这种方式,我们可以实现在选项改变时隐藏或显示不同的表格。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)