.change()
.change( handler(eventObject) ) 返回: jQuery
描述: 為 "change" 事件綁定一個(gè)處理函數(shù),或者觸發(fā)元素上的 "change" 事件。
-
version added: 1.0.change( handler(eventObject) )
handler(eventObject)每次事件觸發(fā)時(shí)會(huì)執(zhí)行的函數(shù)。
-
version added: 1.4.3.change( [ eventData ], handler(eventObject) )
eventData將要傳遞給事件處理函數(shù)的數(shù)據(jù)映射。
handler(eventObject)每次事件觸發(fā)時(shí)會(huì)執(zhí)行的函數(shù)。
version added: 1.0.change()
這個(gè)函數(shù)的第一種用法是 .bind('change', handler) 的快捷方式,第二種用法是 .bind('change') 的快捷方式。
一個(gè)元素的值改變的時(shí)候?qū)⒂|發(fā)change事件。此事件僅限于<input>元素,<textarea>框和<select>元素。對(duì)于選擇框,復(fù)選框和單選按鈕,當(dāng)用戶用鼠標(biāo)作出選擇,該事件立即觸發(fā),但對(duì)于其他類型元素,該事件觸發(fā)將推遲到元素失去焦點(diǎn)。
舉例來(lái)說(shuō),請(qǐng)看下面的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)下拉菜單中第二個(gè)選項(xiàng)被選擇,警報(bào)顯示。如果我們改變了在這一領(lǐng)域的文本,然后點(diǎn)擊警報(bào)也會(huì)顯示。如果該域的內(nèi)容沒(méi)有變化失去焦點(diǎn),該事件不會(huì)被觸發(fā)。點(diǎn)擊另一個(gè)元素時(shí),我們可以手動(dòng)觸發(fā)這個(gè)事件:
$('#other').click(function() {
$('.target').change();
});
這些代碼執(zhí)行后,點(diǎn)擊Trigger the handler也提醒消息。該信息將顯示兩次,因?yàn)楸韱卧囟冀壎?code>change事件處的理函數(shù)。
在jQuery 1.4中 change事件是冒泡的,在Internet Explorer和其他瀏覽器中運(yùn)行是一樣的。.
例子:
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
});