事件是互動式頁面的骨架。jQuery 把這件事整理得相當清爽,主要包括下面幾個方法。
$("p").bind("mouseenter mouseleave", function(e){
$(this).toggleClass("over");
});
$(document).unbind('ready');若不帶參數,則清除所有事件處理程序。
$("#unbind").click(function () {
$("#theone").unbind('click', aClick);
});
$("button:first").trigger('click');
a 元素的跳轉。
$("input").triggerHandler("focus");
$("div").one("click", function(){
// 只會執行一次
});
xxx(fn) 是綁定處理程序,不帶參數 xxx() 則是觸發事件。從 1.2 版起,事件支援命名空間,這讓外掛作者可以只管理自己掛上去的那一份處理程序:
$("div").bind("click", function(){ alert("hello"); });
$("div").bind("click.plugin", function(){ alert("goodbye"); });
$("div").trigger("click!"); // 只會 alert("hello")
加上 .plugin 的綁定被歸入特定命名空間,而 trigger("click!") 的驚嘆號語法則表示「只觸發不屬於任何命名空間的事件」。
下面的範例示範如何同時掛上 propertychange 與 change:前者即時把 textarea 的內容同步到下方 div,後者在值改變時跳出提示。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Events</title>
<script src="../scripts/jquery-1.2.3.intellisense.js"
type="text/javascript"></script>
<style type="text/css">
textarea { height: 118px; width: 280px; }
</style>
<script type="text/javascript">
$(function(){
$('textarea')
.bind('propertychange',function(){
$('#result').html($('textarea').val())
})
.bind('change',function(){
alert($('textarea').val());
});
});
</script>
</head>
<body>
<textarea></textarea>
<div id='result'></div>
</body>
</html>
執行效果如下:

值得留意的是,propertychange 屬於 IE 特有的私有事件,並非跨瀏覽器的標準做法;正式專案裡若要即時偵測輸入變化,應以 input 事件為主。
參考資料:https://docs.jquery.com/Events