简体   繁体   English

如何在插件脚本之外调用jQuery插件函数

[英]How to call a jquery plugin function outside plugin script

I have below script code 我有以下脚本代码

    (function($) {
        $.fn.youamaAjaxLogin = function(options) {

            function start() {
                //start
            }
            ....

How can I call function start() outside 我如何在外面调用函数start()

(function($) {

Please help 请帮忙

Assuming start() uses variables/function also defined within its parent anonymous function, the easiest way I can think of is to create a variable outside of jQuery, which you assign. 假设start()使用也在其父匿名函数中定义的变量/函数,我想到的最简单的方法是在jQuery外部创建一个变量,然后对其进行分配。 Then you can call it both inside the jQuery and outside the jQuery. 然后,您既可以在jQuery内部也可以在jQuery外调用它。

Note: the downside of this is that you can only call start(); 注意:这样做的缺点是只能调用start(); once the page has finished loading. 页面加载完成后。 If you try and call start(); 如果您尝试调用start(); before that, it will cause console errors. 在此之前,它将导致控制台错误。

Here's an example... 这是一个例子

 var start = null; $(function(){ var exampleVariable = "hello world"; start = function() { alert(exampleVariable); } // You can call the function as normal here... // start(); }); // You cannot call it here, because the page won't have loaded, so start won't be defined // start(); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" onclick="start();" value="Call Function"/> 

Make sure that in the header of your page you include jQuery first before you add the plugin. 在添加插件之前,请确保在页面标题中首先包含jQuery。 Then after that, you can add the script tag of your own javascript files that use the plugin. 然后,您可以在使用该插件的自己的javascript文件中添加脚本标签。 So: 所以:

<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<!-- Plugin -->
<script src="https://code.jquery.com/ui/1.11.3/jquery-ui.min.js"></script>
<!-- MyFile -->
<script src="/js/MyFile.js"></script>

Then your file will be able to use all the plugin functions. 然后,您的文件将能够使用所有插件功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM