Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用插件内部的函数_Javascript_Jquery_Function_Jquery Plugins - Fatal编程技术网

Javascript 使用插件内部的函数

Javascript 使用插件内部的函数,javascript,jquery,function,jquery-plugins,Javascript,Jquery,Function,Jquery Plugins,我写了一个小小的jQuery按钮插件——它包含一个应用onclick函数的方法——下面是代码 (function ($) { $.fn.tButton = function () { this.setFN = function(fn) { alert("function set."); } }; })(jQuery); 我正在使用此代码初始化它(在div上): var-button=$(“#myButton”).tButton() 现在的

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

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

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

var-button=$(“#myButton”).tButton()

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

button.setFN(function(){dosomething();});
我收到一个错误:
button.setFN不是一个函数

我已经试过了,但是没有用。
有人知道怎么回事吗?

功能是t按钮。如果应该这样读:

var button = $("#myButton").tButton(function(){dosomething();});
$("button").tButton(function(){ ... });
// or
$("button").data('TButton').setFN( function(){ ... } );

您没有从tButton函数返回任何内容,因此tButton的值不是您认为的值。尝试从tButton()返回
this
,以便将jQuery对象从中取出。另外,我认为这不是一个好方法,因为您基本上是以非标准方式扩展jQuery。更好的方法是让tButton将回调函数作为参数,并将其仅应用于匹配的元素。我还将使用不同的模式来定义插件(类似于UI插件)


以下是可用于执行此操作的模式:

$.TButton = function(el){
    var $el = $(el);
    $el.data('TButton', this); // Store a reference to the TButton object on the DOM element
    // Use this.functionName to make it "public"
    this.setFN = function(callback){
       // Namespace the click events so you don't accidently remove
       // other click events bound to the button.
       $el.unbind('click.tbutton').bind('click.tbutton', callback );
    }
}

$.fn.tButton = function(func){
   return this.each(function(){ // Don't break the chain
      if(! func){ // If no parameter is passed, this is a constructor
        (new $.TButton(this));
      } else { // If the parameter (expected to be a function), call setFN
         var button = $(this).data('TButton');
         if(button) button.setFN(func);
      }
   });          
}
现在,您可以使用以下方法进行初始化:

$("button").tButton();
并且可以通过以下两种方式调用
setFN

var button = $("#myButton").tButton(function(){dosomething();});
$("button").tButton(function(){ ... });
// or
$("button").data('TButton').setFN( function(){ ... } );

setFN涉及哪些方面?:/我尝试在tButton函数的末尾添加return,这是相同的错误。我认为您对jquery标准的看法是正确的,但我需要能够在之后分配/更改按钮函数,然后让函数接受多个参数,并根据这些参数执行不同的操作。例如,如果参数列表是字符串“click”和函数,请将click函数重新应用于元素,否则执行正常操作。感谢您的示例-看起来简单明了:)只有一个问题-它不会在firebug中调试。。不知道是不是我的系统。
.extend
是不必要的
$.fn.tButton=function…
也可以正常工作。这只是因为我只添加了一个方法。不管怎样,我都使用相同的模式。