Unable to access global variables (Javascript)

var hours = document.getElementById("hrs").value; // Global variables declared
var mins = document.getElementById("min").value; 
var seconds = document.getElementById("sec").value; 

function random()
{
    alert(hours);
    alert(mins);
    alert(seconds);
}

The result is displayed as undefinedin all three cases.

+4
source share
4 answers

This particular code can be inside the body of an HTML file, and this code is executed before certain HTML elements are created. Thus, a value is undefinedassigned to these values.

So, you can move the value assignment part inside the function itself.

var hours, mins, seconds;

function random()
{
    hours = document.getElementById("hrs").value;
    mins = document.getElementById("min").value; 
    seconds = document.getElementById("sec").value; 

    alert(hours);
    alert(mins);
    alert(seconds);
}

Note 1: Normally, if you are not using the jQuery library, code like this is put in onload. This is evidenced by MDN,when onload is triggered

. , DOM, .

, HTML, , , HTML .

2: , , id HTML hrs, min sec. name id .

+10

, :

, , JavaScript :

var foo = 1;
function bar() {
    if (!foo) {
        var foo = 10;
    }
    alert(foo);
}
bar();

, "10", , , :

var a = 1;
function b() {
    a = 10;
    return;
    function a() {}
}
b();
alert(a);

http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html

+1

script.

, var. var .

+1

, :

var hours = document.getElementById("hrs").value; // Global variables declared
var mins = document.getElementById("min").value; 
var seconds = document.getElementById("sec").value; 

function random()
{
    alert(hours + mins + seconds);
}
<input type="text" id="hrs" value="9" />
<input type="text" id="min" value=":30" /> 
<input type="text" id="sec" value=":25" />

<input type="button" id="submit" value="GetDetails" onclick="random();">
Hide result
0

All Articles