2012-11-29 84 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