jQuery 對事件的處理可以歸納成幾個核心方法,把這些搞熟,日常九成的互動需求都能應付。
$("p").bind("mouseenter mouseleave", function (e) {
$(this).toggleClass("over");
});
$("#unbind").click(function () {
$("#theone").unbind('click', aClick);
});
// 移除 ready 上的處理函數
$(document).unbind('ready');
$("button:first").trigger('click');
$("input").triggerHandler("focus");
$("div").one("click", function () { });
jQuery 1.2 引入了命名空間機制,讓你能替同一事件的不同處理函數分類,之後可以只移除或觸發特定命名空間下的處理函數,不會誤傷其他程式:
$("div").bind("click", function () { alert("hello"); });
$("div").bind("click.plugin", function () { alert("goodbye"); });
$("div").trigger("click!"); // 只觸發沒有命名空間的,結果是 hello
<!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>
實際運行後,在 textarea 中輸入內容時,右方的 div 會即時同步顯示;離開輸入框時則跳出提示。
更多事件方法可參考官方文件:https://docs.jquery.com/Events