.change()
.change( handler(eventObject) ) 返回: jQuery
描述: 為 "change" 事件綁定一個處理函數(shù),或者觸發(fā)元素上的 "change" 事件。
-
version added: 1.0.change( handler(eventObject) )
handler(eventObject)每次事件觸發(fā)時會執(zhí)行的函數(shù)。
-
version added: 1.4.3.change( [ eventData ], handler(eventObject) )
eventData將要傳遞給事件處理函數(shù)的數(shù)據(jù)映射。
handler(eventObject)每次事件觸發(fā)時會執(zhí)行的函數(shù)。
version added: 1.0.change()
這個函數(shù)的第一種用法是 .bind('change', handler) 的快捷方式,第二種用法是 .bind('change') 的快捷方式。
一個元素的值改變的時候?qū)⒂|發(fā)change事件。此事件僅限于<input>元素,<textarea>框和<select>元素。對于選擇框,復(fù)選框和單選按鈕,當(dāng)用戶用鼠標(biāo)作出選擇,該事件立即觸發(fā),但對于其他類型元素,該事件觸發(fā)將推遲到元素失去焦點。
舉例來說,請看下面的HTML:
<form>
<input class="target" type="text" value="Field 1" />
<select class="target">
<option value="option1" selected="selected">Option 1</option>
<option value="option2">Option 2</option>
</select>
</form>
<div id="other">
Trigger the handler
</div>
事件處理函數(shù)可以綁定到文本輸入和選擇框:
$('.target').change(function() {
alert('Handler for .change() called.');
});
現(xiàn)在,當(dāng)下拉菜單中第二個選項被選擇,警報顯示。如果我們改變了在這一領(lǐng)域的文本,然后點擊警報也會顯示。如果該域的內(nèi)容沒有變化失去焦點,該事件不會被觸發(fā)。點擊另一個元素時,我們可以手動觸發(fā)這個事件:
$('#other').click(function() {
$('.target').change();
});
這些代碼執(zhí)行后,點擊Trigger the handler也提醒消息。該信息將顯示兩次,因為表單元素都綁定了change事件處的理函數(shù)。
在jQuery 1.4中 change事件是冒泡的,在Internet Explorer和其他瀏覽器中運行是一樣的。.
例子:
Example: Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw.
<!DOCTYPE html>
<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
</script>
</body>
</html>
Demo:
Example: To add a validity test to all text input elements:
$("input[type='text']").change( function() {
// check input ($(this).val()) for validity here
});