- 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.jquery.com/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.jquery.com/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.jquery.com/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
廣告
