从jquery插件中的事件内部访问函数

时间:2013-07-03 12:14:19

标签: jquery events plugins this

我已经制作了一个包含点击事件和功能的插件:

// my function
jQuery.fn.runSlideshow = function() {

  // in here I could write:
  jQuery(this).runSlideshow();
  // to call itself again
});

jQuery(this).find(".navigation-wrap a").click(function(ev){
  ev.preventDefault();
  // some code


  // in here, jQuery(this) points to the <a>-tag I clicked on
  alert(jQuery(this).html());


  // but now I want to call the function..
  jQuery(this).runSlideshow(); // won't work
  jQuery.fn.runSlideshow();  // won't work either

})

我知道它现在无法正常工作,因为在点击事件中,我很难引用我点击的元素并且无法返回到&#34;功能-root&#34 ;.不知道该怎么做吗?

1 个答案:

答案 0 :(得分:0)

这对我来说很好:请参阅my jsfiddle

// my function
jQuery.fn.runSlideshow = function(i) {
  console.log('in runSlideshow i = ' + i);

  // in here I could write:
  if (i > 0) jQuery(this).runSlideshow(i-1);
  // to call itself again
};

$(".navigation-wrap a").click(function(ev){
    ev.preventDefault();
  // some code

  // in here, jQuery(this) points to the <a>-tag I clicked on
  alert(jQuery(this).html());

  // but now I want to call the function..
    jQuery(this).runSlideshow(3); //  works
    console.log('call again');
    jQuery.fn.runSlideshow(2);  // works twoo

});
相关问题