如何使用jQuery将选定的值重置为默认值
任务是在jQuery的帮助下将选择元素的值重置为默认值。有两种方法在下面讨论。
方法1:首先使用jQuery选择器选择选项,然后使用prop()方法来获取其属性。如果属性被选中,那么通过使用defaultSelected属性返回默认值。
- 示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
Reset select value to
default with JQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"></p>
<select id="select">
<option value="GFG_1">GFG_1</option>
<option value="GFG_2" selected="selected">
GFG_2
</option>
<option value="GFG_3">GFG_3</option>
<button onclick="GFG_Fun()">
Click Here
<p id="GFG_DOWN"></p>
<script>
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Select a different option "
+ "and then click on the button to "
+ "perform the operation";
function GFG_Fun() {
$('#select option').prop('selected', function () {
return this.defaultSelected;
});
el_down.innerHTML = "Default selected";
}
</script>
</body>
</html>
- 输出:
方法2:首先,使用jQuery选择器选择选项,然后使用each()方法来获取其属性。如果该属性被选中,则通过defaultSelected属性返回默认值
- 示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
Reset select value to
default with JQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP"></p>
<select id="select">
<option value="GFG_1">GFG_1</option>
<option value="GFG_2" selected="selected">
GFG_2
</option>
<option value="GFG_3">GFG_3</option>
<button onclick="GFG_Fun()">
Click Here
<p id="GFG_DOWN"></p>
<script>
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Select a different option "
+ "and then click on the button to "
+ "perform the operation";
function GFG_Fun() {
$('#select option').each(function () {
if (this.defaultSelected) {
this.selected = true;
return false;
}
});
el_down.innerHTML = "Default selected";
}
</script>
</body>
</html>
- 输出:
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它以其 “少写多做 “的理念而广为人知。
你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。