点击jQuery插件中的事件

fre*_*ill 3 jquery

我想用jQuery插件做一些相对简单的事情.我只是不完全确定它内部的点击事件.

这是一个有效的简单例子......

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

};

$("div").testy();
Run Code Online (Sandbox Code Playgroud)

现在,如果不是写作testElem.addClass('highlighted');,我说this.addClass('highlighted');,我会得到这个错误:Uncaught TypeError: Object #<HTMLParagraphElement> has no method 'addClass'

我理解this在这种情况下引用jQuery.我只是通过重用变量来实现它,但这感觉不对.我如何定位我点击的东西?

例如,如果我只是编写脚本,我会写这样的东西:

$('a').click(function(){
  $(this).addClass('active');
});
Run Code Online (Sandbox Code Playgroud)

如何仅针对指定a元素内的元素进行此操作?

Mel*_*igy 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    
};
Run Code Online (Sandbox Code Playgroud)

这是一个更好的例子,它遵循jQuery插件的最佳实践(通过返回each()为你的插件调用的jQuery对象来允许链接):

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