HTML表格中,下拉菜单选定值后,点击按钮将该下拉菜单替换为选定的值,点击另一个按钮则恢复
时间: 2023-06-19 12:03:00 浏览: 32
你可以使用JavaScript代码来实现这个功能。
首先,在HTML表格中添加一个下拉菜单和两个按钮,如下所示:
```html
<table>
<tr>
<td>
<select id="mySelect">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
</select>
</td>
<td>
<button onclick="replaceSelect()">Replace</button>
<button onclick="resetSelect()">Reset</button>
</td>
</tr>
</table>
```
其中,`id="mySelect"` 表示下拉菜单的ID,`replaceSelect()` 和 `resetSelect()` 是两个按钮的点击事件。
然后,在JavaScript中定义这两个函数:
```javascript
function replaceSelect() {
var select = document.getElementById("mySelect");
var selectedValue = select.options[select.selectedIndex].value;
var replaceText = document.createTextNode(selectedValue);
select.parentNode.replaceChild(replaceText, select);
}
function resetSelect() {
var select = document.createElement("select");
select.id = "mySelect";
var option1 = document.createElement("option");
option1.value = "value1";
option1.text = "Value 1";
var option2 = document.createElement("option");
option2.value = "value2";
option2.text = "Value 2";
var option3 = document.createElement("option");
option3.value = "value3";
option3.text = "Value 3";
select.appendChild(option1);
select.appendChild(option2);
select.appendChild(option3);
var oldText = document.getElementById("mySelect").firstChild;
oldText.parentNode.replaceChild(select, oldText);
}
```
`replaceSelect()` 函数将选定的值替换为文本节点,并用 `replaceChild()` 方法替换原始的下拉菜单。
`resetSelect()` 函数将原始的下拉菜单重新创建,并用 `replaceChild()` 方法替换文本节点。