使用JavaScript把input标签换成select标签
时间: 2024-03-10 08:48:33 浏览: 33
可以使用JavaScript来将一个input元素转换为select元素。以下是一个示例代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Convert input to select</title>
</head>
<body>
<label for="myInput">请选择一个选项:</label>
<input type="text" id="myInput" name="myInput" value="选项1">
<button onclick="convertInputToSelect()">转换为下拉列表</button>
<script>
function convertInputToSelect() {
// 获取 input 元素
var input = document.getElementById("myInput");
// 创建 select 元素
var select = document.createElement("select");
select.setAttribute("name", input.getAttribute("name"));
select.setAttribute("id", input.getAttribute("id"));
// 创建选项元素
var option1 = document.createElement("option");
option1.setAttribute("value", "选项1");
option1.textContent = "选项1";
var option2 = document.createElement("option");
option2.setAttribute("value", "选项2");
option2.textContent = "选项2";
var option3 = document.createElement("option");
option3.setAttribute("value", "选项3");
option3.textContent = "选项3";
// 添加选项元素到 select 元素中
select.appendChild(option1);
select.appendChild(option2);
select.appendChild(option3);
// 替换 input 元素为 select 元素
input.parentNode.replaceChild(select, input);
}
</script>
</body>
</html>
```
在上面的示例中,我们首先创建一个input元素和一个按钮,然后在点击按钮时调用convertInputToSelect函数。在函数中,我们首先获取input元素,然后创建一个select元素,并根据input元素的属性设置select元素的name和id属性。接着,我们创建了三个option元素,并将它们添加到select元素中。最后,我们使用parentNode.replaceChild()方法将input元素替换为select元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)