2013-07-18 42 views
0

我想知道如何使此代碼工作:http://jsfiddle.net/LBXVd/2/。這幾乎是乾淨jqueryboilerplate,我感興趣的是這部分代碼:如何在單擊後調用對象函數

Plugin.prototype = { 

    init: function() { 

     /// create element <a> with click function 
     myEl = $('<a/>', { 
      href: '#', 
      text: '###', 
      click: function(e){this._handler();} 
    }); 
    $('ul').before(myEl); 
    }, 


    //handler for click events on my <a> element... 
    _handler: function(el, options) { 
     alert("my handler called"); 
    } 
}; 

我如何可以調用_handler點擊創建的元素後?

謝謝!

回答

3

你的jsfiddle是不是非常有幫助的,因爲它沒有顯示出任何結果......不過,我認爲這是因爲thisthis._handler()呼叫不是你的想法(這是<a>元素,而不是原型對象)。

嘗試

init: function() { 

    var self = this; // **** 

    /// create element <a> with click function 
    myEl = $('<a/>', { 
     href: '#', 
     text: '###', 
     click: function(e){self._handler();} // **** 
}); 
+0

謝謝您的回答。我修好了我的jsfiddle並嘗試了你的代碼。有用! – user2595304

+0

你可能想通過接受我的答案來標記你的問題。 ;-) – obecker

相關問題