在jQuery插件中处理点击事件

3

我希望使用一个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元素来完成此操作?

所以您想要将类添加到div中,对吗? - PSL
请查看此链接:http://jsfiddle.net/zzWEb/ - PSL
2个回答

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()来支持链式调用你的插件):

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


1
这是一个非常棒的回复。你比官方的jQuery文档更清晰地解释了它们。他们有点忽略了在插件上下文中return this.each()的工作原理,但是你的jsFiddle非常完美。谢谢! - freshyill
1
非常感谢您的巧妙解释。它帮助我将一个普通函数转换为插件。非常感谢@Meligy。 - Vel Murugan S

0

像这样做:

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

1
这导致出现错误 Uncaught TypeError: Object #<HTMLParagraphElement> has no method 'css' - freshyill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接