Accessing variable from different function

后端 未结 2 1753
清歌不尽
清歌不尽 2021-01-29 06:49

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



        
相关标签:
2条回答
  • 2021-01-29 07:47

    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);
    }
    
    0 讨论(0)
  • 2021-01-29 07:52

    It is not possible to access a function's local variables from outside of that function, so you have four options:

    1. Declare a global variable!
    2. Write a separate function that grabs the value for you
    3. Create an object that contains the value you need
    4. Grab the value from within your new function using getElementById()
    0 讨论(0)
提交回复
热议问题