2010-07-13 64 views
2

我正在爲jQuery創建一個插件。我不會嘗試在這裏解釋插件,所以讓我們簡單地說,當你點擊目標元素時,我的插件會打開警報。這是我的插件的簡單版本。

(function($) { 

    // Options 
    var defaults = { 
     message: 'Default message' 
    }; 

    var options = $.extend(defaults, options); 

    $.fn.jAlert = function(options) { 
     return this.each(function(){ 

      var $this = $(this); 

      $this.click(function(){ 
       alert(options.message); 
      }); 

     }); 
    }; 
})(jQuery); 

我可以得到那麼多。它效果很好。但是,如果我把我的插件是這樣的:

$('h1.simon').plugin({ message: 'Hello ' + $(this).attr('class') }); 

的消息「你好未定義」,我寧願它是「你好西蒙」(類的H1標籤的)返回。

我確定這是最簡單的事情,但我甚至不知道我應該用Google去尋找解決方案。

任何幫助將不勝感激!

乾杯,
威爾

更新:

約打了一下後,這似乎工作...我不知道爲什麼!我不認爲我真的瞭解範圍。我想我會去做一些閱讀。

$('h1.simon').click(function(){ 
    $(this).jAlert({ 
     icon: 'Hello ' + $(this).attr('class') 
    }); 
}); 
+0

$(這)是指你指的是任何封閉範圍,而不是對象。 – 2010-07-14 00:04:11

回答

2

保存到元素的引用:

var $el = $('h1.simon'); 
$el.plugin({ message: 'Hello ' + $el.attr('class') }); 

否則thiswindow不具有一個類。

+1

你不需要'$(el)'嗎?它應該只是'el'(保存處理)。 – 2010-07-14 00:05:07

+0

這解決了這個問題,謝謝,但有沒有一種方法將此插入到插件JavaScript中,以便調用該插件儘可能簡單?理想情況下,允許我使用$(this)。 再次感謝! – will 2010-07-14 00:07:43

0

在您所呼叫的插件,通過這些選項的時間.. thiswindow而不是元素,你似乎期望

+2

不一定。這取決於他們調用插件的範圍。如果他們做了'$('a')。click(function(){$('h1.simon')....})''那麼它不會引用窗口。但在任何情況下,它都不涉及OP想要的內容。 – 2010-07-14 00:08:01

+0

是的,這是問題,但我該如何改變這個問題? – will 2010-08-24 16:30:10

2

如果你希望能夠使用this爲了方便起見,你可以讓message接受返回您想要顯示的值的函數。

試試看:http://jsfiddle.net/9hyJc/

(function($) { 

    $.fn.jAlert = function(options) { 

    // Options 
    var defaults = { 
     message: 'Default message' 
    }; 

    var options = $.extend(defaults, options); 

     return this.each(function(){ 

      var $this = $(this); 

      $this.click(function(){ 
       if($.isFunction(options.message)) { 
         // If it is a function, call it, 
         // setting "this" to the current element 
        alert(options.message.call(this)); 
       } else { 
         // Otherwise, assume it is a string 
        alert(options.message); 
       } 
      }); 

     }); 
    }; 
})(jQuery); 

$('h1.simon').jAlert({ message: function() { return 'Hello ' + $(this).attr('class'); } }); 
相關問題