我有一个功能,可以从url中删除youtube id.然后我希望每页使用这个函数10次(在wordpress循环中).

当我在函数脚本标记中向其提供url时,该函数非常有效,但当我在循环中启动一组新的脚本标记时,它就不起作用了.

我需要知道如何使用我的函数而不首先声明它.

这是我在标题中的代码:

 <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 defined which makes sense, because its not. Am I able to 'globally' declare this function?

推荐答案

有两个选项,将其添加到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 question about using var functionName = function () {} vs function functionName() {}, and this article about variable scope.

Jquery相关问答推荐

通过 Ajax POST 将按钮值从 HTML 发送到 Flask 时出现空数据

使用 shell 脚本判断 json 数组响应是否具有特定用户名和状态的 jq 命令

Twitter Bootstrap 是否包含 jQuery?

如何制作 AngularJS 指令来停止传播?

我们如何在不重新加载页面的情况下使用 javascript/jQuery 更新 URL 或查询字符串?

使用 jQuery Validate 确认密码

如何设置缓存:jQuery.get 调用中的 false

如何使用 jQuery 清空输入值?

jQuery UI 自动完成宽度未正确设置

如何禁用在div内单击

jQuery 序列化不注册复选框

使用 JQuery 更改 :before css Select 器的宽度属性

如何在 Jquery 中将 delay() 与 show() 和 hide() 一起使用

Bootstrap 3.0 弹出框和工具提示

jQuery - 使用发布数据重定向

所有但不是jQuery Select 器

更改 Eclipse 设置以忽略特定文件上的错误

延迟jquery悬停事件?

如何在没有鼠标事件的情况下在 jQuery 中获取鼠标位置?

如何使用 bootstrap 中的 selectpicker 插件在 Select 时设置选定值