JS 获取select选中的文本
在前端开发中,经常会遇到需要获取 select 元素选中的文本的需求。在这篇文章中,我将介绍如何使用 JavaScript 来获取 select 元素当前选中的文本内容,并给出一些示例代码来演示其用法。
获取选中的文本
要获取 select 元素当前选中的文本内容,我们可以通过以下步骤实现:
- 获取 select 元素的 DOM 对象
- 使用
selectedIndex
属性获取选中项的索引 - 使用
options[index].text
获取选中项的文本内容
下面是一个示例代码,演示了如何通过 JavaScript 获取 select 元素选中的文本:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Selected Text from Select Element</title>
</head>
<body>
<select id="mySelect">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
<button onclick="getSelectedText()">Get Selected Text</button>
<script>
function getSelectedText() {
var selectElement = document.getElementById("mySelect");
var selectedIndex = selectElement.selectedIndex;
var selectedText = selectElement.options[selectedIndex].text;
alert("Selected text: " + selectedText);
}
</script>
</body>
</html>
在上面的示例代码中,我们首先获取了 id 为 mySelect
的 select 元素,然后通过 selectedIndex
属性获取了选中项的索引,最后通过 options[index].text
获取了选中项的文本内容,并通过 alert
方法弹出选中的文本。
示例运行结果
当我们选择不同的选项并点击按钮时,会弹出相应的选中文本:
- 选择 Option 1,点击按钮,弹出:Selected text: Option 1
- 选择 Option 2,点击按钮,弹出:Selected text: Option 2
- 选择 Option 3,点击按钮,弹出:Selected text: Option 3
通过上面的示例代码和运行结果,我们可以看到如何使用 JavaScript 来获取 select 元素选中的文本内容。