无涯教程-jQuery - html( val )方法函数
发布人:shili8
发布时间:2025-02-22 08:28
阅读次数:0
**jQuery 教程**
**第6 部分: jQuery 中的 `val()` 方法**
在本教程的前几部分中,我们已经学习了 jQuery 的基本使用、选择器、事件处理等知识。今天我们要讲解的是 jQuery 中非常重要的一个方法——`val()`。
**什么是 `val()` 方法?**
`val()` 方法用于获取或设置表单元素(如输入框、下拉菜单等)的值。它可以用来读取或修改表单元素的内容。
**使用 `val()` 方法的例子**
###1. 获取表单元素的值
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src=" /></head>
<body>
<input type="text" id="username" value="John Doe">
<button id="getVal">获取值</button>
<script>
$(document).ready(function() {
$("#getVal").click(function() {
var val = $("#username").val();
alert("用户名:" + val);
});
});
</script>
</body>
</html>
在上面的例子中,我们使用 `val()` 方法获取了输入框的值,并将其显示在一个弹出窗口中。
###2. 设置表单元素的值
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src=" /></head>
<body>
<input type="text" id="username" value="John Doe">
<button id="setVal">设置值</button>
<script>
$(document).ready(function() {
$("#setVal").click(function() {
$("#username").val("Jane Doe");
});
});
</script>
</body>
</html>
在上面的例子中,我们使用 `val()` 方法设置了输入框的值。
###3. 获取多个表单元素的值
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src=" /></head>
<body>
<input type="text" id="username" value="John Doe">
<input type="password" id="password" value="123456">
<button id="getVals">获取值</button>
<script>
$(document).ready(function() {
$("#getVals").click(function() {
var username = $("#username").val();
var password = $("#password").val();
alert("用户名:" + username + "
密码:" + password);
});
});
</script>
</body>
</html>
在上面的例子中,我们使用 `val()` 方法获取了两个输入框的值,并将其显示在一个弹出窗口中。
###4. 设置多个表单元素的值
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src=" /></head>
<body>
<input type="text" id="username" value="John Doe">
<input type="password" id="password" value="123456">
<button id="setVals">设置值</button>
<script>
$(document).ready(function() {
$("#setVals").click(function() {
$("#username").val("Jane Doe");
$("#password").val("654321");
});
});
</script>
</body>
</html>
在上面的例子中,我们使用 `val()` 方法设置了两个输入框的值。
**总结**
`val()` 方法是 jQuery 中非常重要的一个方法,它可以用来获取或设置表单元素的值。通过本教程,你已经学习了如何使用 `val()` 方法获取和设置表单元素的值,包括获取多个表单元素的值和设置多个表单元素的值。

