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

后端 未结 6 1734
悲&欢浪女
悲&欢浪女 2020-12-04 08:17

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).

The function works great when I fe

6条回答
  •  一向
    一向 (楼主)
    2020-12-04 08:46

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

    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 question about using var functionName = function () {} vs function functionName() {}, and this article about variable scope.

提交回复
热议问题