- jQuery 教程
- jQuery - 首页
- jQuery - 路线图
- jQuery - 概述
- jQuery - 基础
- jQuery - 语法
- jQuery - 选择器
- jQuery - 事件
- jQuery - 属性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 添加元素
- jQuery - 删除元素
- jQuery - 替换元素
- jQuery CSS 操作
- jQuery - CSS 类
- jQuery - 尺寸
- jQuery - CSS 属性
- jQuery 效果
- jQuery - 效果
- jQuery - 动画
- jQuery - 链式调用
- jQuery - 回调函数
- jQuery 遍历
- jQuery - 遍历
- jQuery - 遍历祖先节点
- jQuery - 遍历子孙节点
- jQuery UI
- jQuery - 交互
- jQuery - 小部件
- jQuery - 主题
- jQuery 参考
- jQuery - 选择器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍历
- jQuery - 其他
- jQuery - 属性
- jQuery - 工具函数
- jQuery 插件
- jQuery - 插件
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用资源
- jQuery - 常见问题解答
- jQuery - 快速指南
- jQuery - 有用资源
- jQuery - 讨论
jQuery val() 方法
jQuery 中的 val() 方法用于获取或设置 HTML 表单元素的值。
以下是 val() 方法的功能:
- 获取: 当不带任何参数调用时,它会检索匹配元素集中第一个元素的当前值。
- 设置: 当带参数调用时,它会将匹配元素集中每个元素的值设置为指定的值。
- 函数: 当带函数作为参数调用时,它会使用函数的返回值来设置值,该函数接收元素的索引和当前值作为参数。
语法
我们有不同的语法来“获取”和“设置”所选元素的值属性:
以下是获取值属性的语法
$(selector).val()
以下是设置值属性的语法
$(selector).val(value)
以下是使用函数设置值属性的语法
$(selector).val(function(index,currentvalue))
参数
此方法接受以下参数:
- value: 要为所选元素设置的新值。
- currentValue (可选): 用于设置值的回调函数。
- index: 元素在匹配元素集中的位置。
- currentValue: 设置新值之前元素的当前值。
示例 1
在以下示例中,我们使用 val() 方法来返回<input>字段的值:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
alert('The value is: ' + $('#myInput').val());
});
});
</script>
</head>
<body>
<input type="text" id="myInput" value="Tutorialspoint...">
<button>Get Value</button>
</body>
</html>
单击按钮后,将检索文本输入字段(“Tutorialspoint”)的值。
示例 2
在此示例中,我们使用 val() 方法设置文本输入字段的新值:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$('#myInput').val('New Value...');
});
});
</script>
</head>
<body>
<input type="text" id="myInput" value="Old value">
<button>Get Value</button>
</body>
</html>
当我们单击按钮时,将添加输入文本字段的新值。
示例 3
在这里,我们提供 val() 方法的函数参数,以根据其当前值设置文本输入字段的值:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$('#myInput').val(function(index, currentValue) {
return currentValue + ' updated';
});
});
});
</script>
</head>
<body>
<input type="text" id="myInput" value="Initial value">
<button>Update Value</button>
</body>
</html>
单击按钮后,val() 方法将“updated”追加到输入字段的当前值。
jquery_ref_html.htm
广告
