Javascript 如何使 jQuery.ready 中定义的函数全局可用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2223305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:18:52  来源:igfitidea点击:

How can I make a function defined in jQuery.ready available globally?

javascriptjquery

提问by wesbos

I have a function that strips the youtube id off a url. I then want to use this function 10 time per page (in the wordpress loop).

我有一个函数可以从 url 中删除 youtube id。然后我想每页使用这个函数 10 次(在 wordpress 循环中)。

The function works great when I feed it the url within my function script tags, but when I start a new set of script tags within the loop, it does not work.

当我在我的函数脚本标签中向它提供 url 时,该函数工作得很好,但是当我在循环中启动一组新的脚本标签时,它不起作用。

I need to know how I can use my function without declaring it all first.

我需要知道如何在不首先声明的情况下使用我的函数。

So this is the code I have in the header:

所以这是我在标题中的代码:

 <script type="text/javascript"> 
$(document).ready(function() {
var getList = function(url, gkey){
        var returned = null;
        if (url.indexOf("?") != -1){
          var list = url.split("?")[1].split("&"),
                  gets = [];

          for (var ind in list){
            var kv = list[ind].split("=");
            if (kv.length>0)
                gets[kv[0]] = kv[1];
        }

        returned = gets;

        if (typeof gkey != "undefined")
            if (typeof gets[gkey] != "undefined")
                returned = gets[gkey];

        }

            return returned;

    };


        // THIS WORKS

    alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));


      });

But when I try use this somewhere else on the page, it doesnt work.

但是当我尝试在页面上的其他地方使用它时,它不起作用。

 <script type="text/javascript"> 

      $(document).ready(function() {
              alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
      };
      </script>

Firebug gives me getList is not definedwhich makes sense, because its not. Am I able to 'globally' declare this function?

Firebug 给我getList 没有定义这是有道理的,因为它没有。我可以“全局”声明这个函数吗?

回答by Andy E

You have two options, add it to the windowobject to make it global:

您有两个选择,将其添加到window对象以使其成为全局对象:

window.getList = function(url, gkey){ 
    // etc...
}

or move it from inside the document ready event handler into the global scope:

或者将它从文档就绪事件处理程序内部移动到全局范围:

$(document).ready(function() {  
    alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
});  
var getList = function(url, gkey){  

    var returned = null;  
    if (url.indexOf("?") != -1){  
      var list = url.split("?")[1].split("&"),  
              gets = [];  

      for (var ind in list){  
        var kv = list[ind].split("=");  
        if (kv.length>0)  
            gets[kv[0]] = kv[1];  
    }  

    returned = gets;  

    if (typeof gkey != "undefined")  
        if (typeof gets[gkey] != "undefined")  
            returned = gets[gkey];  

    }  

        return returned;  

};  

You might also want to read this questionabout using var functionName = function () {}vs function functionName() {}, and this articleabout variable scope.

您可能还想阅读有关使用vs 的问题,以及有关变量作用域的文章var functionName = function () {}function functionName() {}

回答by Pointy

Yet another option is to hang the function off the jQuery object itself. That way you avoid polluting the global name space any further:

另一种选择是将函数挂在 jQuery 对象本身之外。这样你就可以避免进一步污染全局命名空间:

jQuery.getlist = function getlist(url, gkey) {
  // ...
}

Then you can get at it with "$.getlist(url, key)"

然后你可以用“$.getlist(url, key)”来获取它

回答by coolest_head

declare getList() outside the ready() function..

在 ready() 函数之外声明 getList() ..

var getList = function(url, gkey){
        var returned = null;
        if (url.indexOf("?") != 
....
....
...
};

Now the getList will work anywhere in the code:

现在 getList 将在代码中的任何地方工作:

$(document).ready( function() {
alert(getList('http://www.youtube.com/watch?v=dm4J5dAUnR4', "v"));
});

The problem was, scope of the getList(.) function.

问题是 getList(.) 函数的范围。

回答by Traveling Tech Guy

Just define it as a regular function at the top of your script:

只需在脚本顶部将其定义为常规函数即可:

<script type="text/javascript">
    function getlist(url, gkey){  
        ...
    }
</script>

回答by milkovsky

You can simply add your function in the $.fnvariable:

您可以简单地在$.fn变量中添加您的函数:

(function ($) {

   $.fn.getList = function() {
       // ...
   };

}(jQuery));

Example usage:

用法示例:

$().getList();

This is what you would typically do while creating a Basic Pluginfor jQuery.

这是您在为 jQuery创建基本插件时通常会做的事情。

回答by Farinha

To declare it as a global function, just get rid of all the jQuery specific bits. Something like this:

要将其声明为全局函数,只需删除所有 jQuery 特定位。像这样的东西:

function getList(url, gkey) {
    var returned = null;
    if (url.indexOf("?") != -1){
    var list = url.split("?")[1].split("&"), gets = [];
    for (var ind in list){
        var kv = list[ind].split("=");
        if (kv.length>0) {
            gets[kv[0]] = kv[1];
        }
    }

    returned = gets;

    if (typeof gkey != "undefined") {
        if (typeof gets[gkey] != "undefined") {
            returned = gets[gkey];
        }
    }

    return returned;
}

And then you should be able to call it from anywhere.

然后你应该可以从任何地方调用它。