使用插件内的函数 [英] Using functions from inside a plugin

查看:88
本文介绍了使用插件内的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小小的jQuery按钮插件 - 它包含了一个应用onclick函数的方法 - 下面是代码:

 (函数($){
$ .fn.tButton = function()
{
this.setFN = function(fn)
{
alert(function set。 );
}
};

})(jQuery);

我使用此代码初始化它(在div上):



var button = $(#myButton)。tButton();



<现在的问题是:当试图应用setFN函数时:

  button.setFN(function(){dosomething(); }); 

出现错误: button.setFN不是函数



我已经尝试使用this.bind,但没有帮助。
任何人都知道什么是错误的?

解决方案

你没有从tButton函数返回任何东西,所以tButton的值是你的想法是什么?尝试从tButton()返回 this ,以便将jQuery对象从中取出。另外,我认为这不是一个好的方法,因为你基本上是以非标准的方式扩展jQuery。更好的方法是让tButton将回调函数作为参数并将其应用于匹配元素。

 (function($){
$ .fn.extend({
tButton:function(callback){
return this.each(function(){
new $ .TButton(this,callback);




$ .TButton = function(elem,callback){
$(elem).click(callback);
};
})(jQuery);


i wrote a little jQuery button plugin - it contains a method for applying the onclick-function - here's the code

(function ($) {
  $.fn.tButton = function () 
  {
    this.setFN = function(fn)
    {
        alert("function set.");
    }
  };

})(jQuery);

i'm using this code to initialize it (on a div):

var button = $("#myButton").tButton();

now the problem: when trying to apply the setFN function:

button.setFN(function(){dosomething();});

i'm getting an error: button.setFN is not a function

i already tried this.bind instead but didn't help. anyone knows what's wrong?

解决方案

You aren't returning anything from the tButton function so the value of tButton isn't what you think it is. Try returning this from tButton() so to get the jQuery object back out of it. Also, I don't think this is a good way to do it as you are basically extending jQuery in a non-standard way. A better way would be to have tButton take the callback function as an argument and apply it to just the matching elements. I would also use a different pattern for defining the plugin (similar to the UI plugins).

(function ($) {
  $.fn.extend( {
      tButton: function(callback) {
          return this.each( function() {
             new $.TButton(this,callback);
          });
      }
  });

  $.TButton = function(elem,callback) {
       $(elem).click(callback);
  };
})(jQuery);

这篇关于使用插件内的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆