DIV CSS 佈局教程網

jQuery .on() 用法解析:事件表單寫法與插件中的實踐
編輯:JavaScript綜合知識     

.on() 是 jQuery 1.7 之後統一的事件綁定入口,取代了 bind、live、delegate。它最實用的能力之一,是一次用物件把多個事件綁在同一個元素上。

完整範例:把 on 用在插件裡

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<title>.on() 示範</title>
</head>
<body>
<input type="button" value="test" id="test">

<script>
$(function () {
  $("#test").hello({ "size": 1 });
});
</script>

<script>
;(function ($) {
  $.fn.hello = function (options) {
    var defaults = { "size": 0 },
        opts = $.extend({}, defaults, options),
        show = {
          play: function (options) {
            var _root = this;
            _root.autoPlay();
            _root.eventClick();
          },
          autoPlay: function () {
            console.log("auto");
          },
          eventClick: function () {
            $("#test").on({
              click:       function () { alert("click"); },
              mouseenter:  function () { alert("enter"); },
              mouseleave:  function () { alert("leave"); }
            });
          }
        };

    return this.each(function () {
      show.play(opts);
    });
  };
})(jQuery);
</script>
</body>
</html>

三種呼叫形式

一、單一事件

$("#btn").on("click", function () { /* ... */ });

二、事件對應表(一次綁多個)

$("#test").on({
  click:       function () { alert("click"); },
  mouseenter:  function () { alert("enter"); },
  mouseleave:  function () { alert("leave"); }
});

三、傳入資料與事件委派

$("#test").on("click", { show: "dd" }, function (e) {
  console.log("click :" + e.data.show);
});

// 委派:把監聽掛在 static 祖先上,selector 放第二參數
$(document).on("click", ".dynamic-btn", function () { /* ... */ });

範例中被註解掉的那兩行,示範的正是第三種:第二個參數傳物件,處理函式裡用 e.data.show 取出。這在迴圈中產生多個 handler 時特別有用,可以避免閉包捕獲錯誤的索引值。

為什麼前面要加分號

;(function ($) { ... })(jQuery);

那個行首分號是防禦性寫法。若上一段腳本以未加分號的表達式結尾,瀏覽器可能把 ( 解析成「呼叫上一個結果」,整段就爆掉。寫插件時加上它幾乎沒有成本,卻能避免難以追查的錯誤。

插件結構的三個要點

掛在 $.fn 上。$.fn.hello = function(){} 才能讓 $("#test").hello() 這種呼叫成立。

用 $.extend 合併預設值。$.extend({}, defaults, options) 讓使用者只需傳要覆寫的鍵,其餘自動沿用預設,且不会污染 defaults 物件本身。

回傳 this.each(...)。這維持了 jQuery 的鏈式呼叫能力,讓 $(".x").hello().css(...) 可以寫下去。少了它,插件就變成鏈條的斷點。

現代對照

// 原生:多事件寫法
el.addEventListener("click", fn);
el.addEventListener("mouseenter", fn2);

// 委派
document.addEventListener("click", function (e) {
  if (e.target.closest(".dynamic-btn")) { /* ... */ }
});

另外提醒:mouseenter/mouseleave 不觸發事件冒泡,因此無法用委派;若需要委派效果,改用 mouseover/mouseout 並自行處理冒泡,或直接用 pointerenter 搭配 closest 判斷。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved