jQuery – 如何在 plugin 套件中,呼叫 callback 時可以使用 $(this)

製作外掛套件 (plugin) 的時候,如果我們想要將 $(this) 等同於 $(“.item”) ,方便在 callback 的時候可以直接使用 $(this) ,該怎麼設計?這小問題困擾了我一些時間,後來才發現原來這麼簡單XD
1 2 3 4 5 |
$(".item").myplugin(function (){ var text = $(this).text(); //Hello World! }) |
直接看這兩種寫法,就會知道怎麼設計了喔
Plugin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
(function ( $ ) { $.fn.myPlugin = function (callback){ callback(this); //只是將 this 放到夾帶的參數 } $.fn.myPlugin2 = function (callback){ callback.call(this); //將 this 指定到 callback } }( jQuery )); |
關鍵的地方就在於 plugin 呼叫 callback 的時候,不要直接使用 callback(this) 而是使用 callback.call(this)。我們看看使用的範例:
Html
1 2 3 |
<a href="" class="item">最新消息</a> |
jQuery
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
$(function (){ $(".item").myPlugin(function (obj){ console.log($(obj)); // [a.item] console.log($(this)); // [Window] // console.log($(this).html()); // Error }) $(".item").myPlugin2(function (obj){ console.log($(obj)); // r.fn.init {} console.log($(this)); // [a.item] console.log($(this).html()); // 最新消息 }) }) |
myPlugin2 中看到,直接用 $(this).html() 就能撈出我們要的資料囉!