如何在JavaScript中创建全局变量? [英] How do I make a Global Variable in JavaScript?

查看:81
本文介绍了如何在JavaScript中创建全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我希望仪表板能够在一个功能中进行修改,然后在另一个功能中显示.有点像java中的公共变量.这可能吗?请参阅下面的代码.

So I would like for dashboard to be able to be modified inside one function, then be displayed in another function. Kind of like a public variable in java. Is this possible? See my code below.

var dashboard = new Array();
function init() {
    getXML(); //1.  goto get XML 2.// XML Parser
    displayXML();
}

function getXML() {
    console.log("getXML REACHED");
    $.ajax({
        type: "GET",
        url: "file:///H:/ModelDisplayV1/ModelDisplayV1/files/dashboard.xml",
        dataType: "xml",
        success: xmlParser
    });
}

function xmlParser(xml) {
    dashboard[0] = 7;
    console.log(dashboard);
});
}

function displayXML() {
    console.log("display xml function reached!!!");
    console.log(dashboard);
}

当我最终尝试获取console.log(dashboard)时,它说dashboard is undefined.我认为,通过在功能之外声明仪表板将是全局的.如何做到这一点,以便可以在一个功能中更改仪表板的内容并在另一个功能中进行检索?

When I finally try and get the console.log(dashboard) it says dashboard is undefined. I thought by declaring dashboard outside of my functions it would be global. How do I make it so I can alter the contents of dashboard in one function and retrieve them in another function?

我比Java更熟悉Java.

I am more familiar with Java as opposed to Javascript.

推荐答案

ajax调用是异步的,因此在实际填充仪表板之前,init()方法中将调用displayXML()函数.而是这样做:

The ajax call is asynchrous, so the displayXML() function is called in the init() method before dashboard is actually filled. So do this instead:

var dashboard = new Array();
function init() {
    getXML(); //1.  goto get XML 2.// XML Parser
}

function getXML() {
    console.log("getXML REACHED");
    $.ajax({
        type: "GET",
        url: "file:///H:/ModelDisplayV1/ModelDisplayV1/files/dashboard.xml",
        dataType: "xml",
        success: xmlParser
    });
}

function xmlParser(xml) {
    dashboard[0] = 7;
    console.log(dashboard);
    displayXML();
});
}

function displayXML() {
    console.log("display xml function reached!!!");
    console.log(dashboard);
}

这篇关于如何在JavaScript中创建全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆