2013-05-12 78 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