2013-05-12 38 views
3

我想用jQuery插件做一些相對簡單的事情。我只是不完全確定它內部的點擊事件。單擊jQuery插件中的事件

這裏是一個可行的簡單的例子...

$.fn.testy = function() { 
    var testElem = this.find('p'); 
    testElem.click(function(){ 
     testElem.addClass('highlighted'); 
     ^^^^^^^^ 
    }); 

}; 

$("div").testy(); 

現在,如果不是寫testElem.addClass('highlighted');,我把this.addClass('highlighted');,我會得到這個錯誤:Uncaught TypeError: Object #<HTMLParagraphElement> has no method 'addClass'

我明白this指的jQuery在這方面。我通過重用變量來實現它,但是感覺不對。我如何瞄準我點擊的東西?

例如,如果我只是寫一個劇本,我會寫這樣的事:

$('a').click(function(){ 
    $(this).addClass('active'); 
}); 

我怎麼能做到這一點,而只針對指定的元素中的a元素?

+0

所以你想添加類到div權利? – PSL 2013-05-12 04:15:15

+0

檢查此http://jsfiddle.net/zzWEb/ – PSL 2013-05-12 04:19:10

回答

5

讓我解釋一下評論:

$.fn.testy = function() { 
    // `this` here refers to all `DIV`s as jQuery objects 

    var testElem = this.find('p'); 
    // `testElem` is now collection of all `P`s from all `DIV`s, as jQuery object 

    testElem.click(function(){ // <<-- 
     // Note you are now inside another function 
     // This function gets called for each `P` 

     // of course you don't want to apply yo all `testElem`, only clicked one 
     // `this` inside the new function is the `P` AS DOM Element not jQuery 
     var $testP = $(this); // just wrapping one `P` in jQuery object 
     // Now you can 
     $testP.addClass('highlighted'); 
     // You didn't need the variable, but for explanation 
    }); // <<-- finished click function 

    // back to plugin function  
}; 

這裏有如下的jQuery插件的最佳實踐(允許鏈通過返回each()爲jQuery的一個更好的例子物件叫你的插件):

http://jsfiddle.net/Meligy/s2wN4/

+1

這是一個很棒的迴應。你做得比官方的jQuery文檔更清晰。它隱藏瞭如何返回this.each()在插件上下文中工作,但是你的jsFiddle是完美的。謝謝! – freshyill 2013-05-13 01:37:41

+0

很高興你喜歡它:) – Meligy 2013-05-13 01:52:21

+1

非常感謝你的聰明解釋。它幫助我將常用功能轉換爲插件。非常感謝@Meligy – 2014-01-29 15:11:17

0

做這樣的:

$(this).addClass('highlighted'); 
+1

這會導致此錯誤'未捕獲的類型錯誤:對象#沒有方法'css' – freshyill 2013-05-12 04:11:00