如何使用jQuery获取特定选项标签的文本
为了选择一个选定的选项或任何特定的选项的文本,jQuery允许通过其特定的选择器轻松做到这一点。选择器是用来选择特定的元素。
例子:这个例子选择了特定选项(GFG_2)标签的文本。
<!DOCTYPE html>
<html>
<head>
<title>
Get text of specific option tag
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<select id='GFG_list'>
<option value='GFG_1'>GFG_A</option>
<option value='GFG_2'>GFG_B</option>
<option value='GFG_3'>GFG_C</option>
</select>
<br><br>
<button id="GFG_Button" onclick = "getText()">
getText
</button>
<p id = "GFG_P" style="color:green;font-size:20px;"></p>
<script>
function getText(){
var el = document.getElementById("GFG_P");
el.innerHTML = $("#GFG_list option[value='GFG_2']").text();
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子:这个例子选择了当前选择的选项标签的文本。
<!DOCTYPE html>
<html>
<head>
<title>
Get text of specific option tag
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<select id='GFG_list'>
<option value='GFG_1'>GFG_A</option>
<option value='GFG_2'>GFG_B</option>
<option value='GFG_3'>GFG_C</option>
</select>
<br><br>
<button id="GFG_Button" onclick = "getText()">
getText
</button>
<p id = "GFG_P" style = "color:green; font-size: 20px;"></p>
<script>
function getText(){
var el = document.getElementById("GFG_P");
el.innerHTML = $("#GFG_list option:selected").text();
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。