javascript - 从多个嵌套函数中获取变量

标签 javascript jquery variables

我正在尝试从多个嵌套函数中获取变量(lib)

var nme='name',lib;

$('script').each(function(){

    var src=$(this).attr('src');

    if(typeof(src)==='undefined'){src='';}

if(src.indexOf(nme)!==-1){

    $.get($(this).attr('src').match(/\w([^ ]+)spbin/)[0]+'/conf/ptmedia.plist',
        function(c){
            $(c).find('key').each(function(){
                if($(this).html()==='MediaLib'){lib=$(this).next().html();}
            });
        }
    );

}
});

if(lib==='some lib'){DO STUFF}

最佳答案

您的问题不在于范围界定,问题在于您有一个异步的 AJAX 调用。 您应该将 HTML 的更改放在回调函数内的 .null 中:

$.get($(this).attr('src').match(/\w([^ ]+)spbin/)[0]+'/conf/ptmedia.plist',
        function(c){
            $(c).find('key').each(function(){
                if($(this).html()==='MediaLib'){lib=$(this).next().html();}

                $('.null').html(lib);
            });
        }
});

在 JavaScript 中,IO 通常是异步的。这意味着当您进行 AJAX 调用时,它不会立即发生,而是等待从 HTTP 请求返回值,然后调用回调。在您的例子中,function(c) 是回调,它会在 AJAX 调用的值到达时执行。

所以实际上您正在将 .nullHTML 内容更新为未定义,因为它在更新之前获取了 lib 的值.

关于javascript - 从多个嵌套函数中获取变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622433/

相关文章:

php - 将 jQuery.ajax 数据同时发送到表单提交

PHP终端模拟器

javascript - Darsain/Sly - 无限循环 - 第一张幻灯片应出现在末尾

jquery .html() 函数问题

variables - Ansible:使命令的输出成为下一个命令的键值项/变量

c - C中bool变量的效用是什么?

javascript - Agenda js 作业立即执行

javascript - 正则表达式 : get word without word before it

javascript - 嵌套状态对象中的回调

MySQL : Use Variable/Function Returned Value in Select