如何使用jQuery从下拉列表中获取选定的文本
我们可以选择文本,也可以使用option:selected属性或使用jQuery中的val()方法来查找文本在下拉列表中的位置。
通过使用val()方法:
val()方法是jQuery内置的一个方法,用于返回或设置所选元素的属性值。
语法 :
$(selector).val(parameter)
参数:参数是可选的。
示例 :
<html>
<head>
<title>jQuery Selector</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("#submit").click(function() {
alert($("#myselection").val());
});
});
</script>
<style>
div {
width: 50%;
height: 200px;
padding: 10px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>The selected value:</p>
<select id="myselection">
<option value="1">First</option>
<option value="2">Second</option>
</select>
<br>
<br>
<button id="submit">Submit</button>
</div>
</body>
</html>
输出 :
在点击按钮之前。
点击按钮后。
通过使用选项:选定:
option:selected方法是jQuery中的一种方式,用于从元素的列表中返回所选择的元素。
语法 :
$("#selector option:selected");
参数:不需要参数。
示例 :
<html>
<head>
<title>jQuery Selector</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
(document).ready(function() {
("#submit").click(function() {
var value = $("#myselection option:selected");
alert(value.text());
});
});
</script>
<style>
div {
width: 50%;
height: 200px;
padding: 10px;
border: 2px solid green;
}
</style>
</head>
<body>
<div>
<p>The selected value:</p>
<select id="myselection">
<option value="1">First</option>
<option value="2">Second</option>
</select>
<br>
<br>
<button id="submit">Submit</button>
</div>
</body>
</html>
输出 :
在点击按钮之前。
点击按钮后。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。