2012-11-29 85 views
1
(function($){ 
    $.fn.the_func = function() { 

     function my_func(){ 
      alert('it works'); 
     } 

     my_func(); 

     // other code 

    }; 
})(jQuery); 

$(window).load(function(){ 
    my_func(); // This way? 
    $.the_func().my_func(); // Or this way? No? 
    $.the_func.my_func(); // No? 
    // ? 
}); 

$(document).ready(function(){ 
    $('div').the_func(); 
}); 

我如何可以调用它包装它的功能外这个功能呢?
我想调用my_func()就像这个代码示例。
(窗口负载函数仅仅是一个例子。)
我想调用从“无处不在” my_func()无内the_func()执行的其他功能或代码。但我想使用the_func()的变量。
With my_func()我想更新存储在参数the_func()中的值。的Jquery/JS:调用jQuery的功能的功能外jQuery的功能

+0

如何将它称为'$(“div”)。the_func(“my_func”)'?这会起作用吗?我不同意你的当前解决方案的意思是......我的意思是,如果你会好起来的与语法,因为这是我知道的热来构建它,使你想 – Ian

回答

2

这里有一个如何我通常写一个插件的例子,可以应用到您的情况:我

http://jsfiddle.net/pMPum/1/

(function ($) { 
    function my_func(element) { 
     console.log("it works: " + element.innerHTML); 
    } 

    var methods = { 
     init: function (options) { 
      console.log("from init"); 
      console.log("options for init: " + JSON.stringify(options)); 
      my_func(this); 
     }, 

     my_func: function (options) { 
      console.log("from my_func"); 
      console.log("options for my_func: " + JSON.stringify(options)); 
      my_func(this); 
     } 
    }; 

    $.fn.the_func = function (method) { 
     var args = arguments; 
     var argss = Array.prototype.slice.call(args, 1); 

     return this.each(function() { 
      if (methods[method]) { 
       methods[method].apply(this, argss); 
      } 
      else if (typeof method === "object" || !method) { 
       methods.init.apply(this, args); 
      } 
      else { 
       $.error("Method " + method + " does not exist on jQuery.the_func"); 
      } 
     }); 
    }; 
})(jQuery); 

$(document).ready(function() { 
    $("div").the_func({ // Same as passing "init" and { } as params 
     test: "testing" 
    }); 
}); 

注意如何制造可以称之为范围内通用my_func功能。 methods中的my_func方法是通过插件语法.the_func()向全世界公开的,而my_func函数是私有的并且无法直接访问。

调用不同方法的语法与大多数/大量的jQuery插件相同。

+0

THX它的工作方式。但如何在“init”函数内调用“my_func”? ..为什么你用“return this.each(func ...)”? –

+0

@JohnDoeSmith刚刚更新了我的答案。我使用'return this.each',以便jQuery插件调用可能发生链接。所以,你可以不喜欢'$( “格”)the_func( “方法”)addClass( “东西”)显示();' - 这可让'the_func'电话后,在应用任何jQuery方法。到原来的选择器 – Ian