从不同的函数访问变量 [英] Accessing variable from different function

查看:89
本文介绍了从不同的函数访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在HTML中使用以下代码创建了一个按钮,单击该按钮会在我的页面中创建一些问题,效果很好.

I have the following code in HTML which creates a button, that when clicked creates some questions in my page, works fine.

<input type="number" name="quantity" id="num_questions" min="1" max="99"><br>
<input type="button" name="go" id="go_button" value="Go" onclick="createQuestions()"><br>

但是,在函数createQuestions()中,我已经在JavaScript中定义了一个变量,该变量基于从我的HTML代码输入的数字,如上所示.

However, within my function createQuestions() I have defined a variable in JavaScript, which is based on a number input from my HTML code, shown above.

var number = document.getElementById('num_questions').value;

我还有另一个按钮,它调用一个单独的函数,但我需要该变量号是我在另一个函数中本地定义的.有什么办法可以获取该变量并在全局范围内使用它?我尝试在函数外定义它,但是由于onclick事件仅调用该函数,因此不会创建变量.

I have another button which calls a separate function but I need that variable number I locally defined in another function. Is there any way I can grab that variable and use it globally? I tried defining it outside my function, but since the onclick event only calls that one function, it won't create the variable.

其他按钮:

<input type="submit" name="submit" value="Create Tree" onclick="displayData()">

推荐答案

根据

According to How to declare a global variable in a .js file you can define a variable before any function is called and then use it in different functions.

var global1 = "I'm a global!";

function setGlobal () {
    global1= document.getElementById('num_questions').value;
}
function testGlobal () {
    alert(global1);
}

这篇关于从不同的函数访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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