简体   繁体   中英

Javascript variable doesn't seem to enter the DOM

<head>
<script>
function setParams() {
    var year = "2011";
}

function showYear() {
    alert("The year is " + year);
}
</script>
</head>
<body>
<input type="submit" onclick="setParams();" value="Set" />
<input type="submit" onclick="showYear();" value="Year" />
</body>

So why does year not enter the dom for alert to read?

Your variable declaration:

var year = "2011";

is a local variable that is only visible inside the function you've declared it in.

If you want it visible globally so other functions can access it, then you must declared it as a global variable where you declare it at the top level of scope outside of any functions:

var year;

function setParams() {
    year = "2011";
}

function showYear() {
    alert("The year is " + year);
}

A variable declared within a function is, by definition, a local variable and is only available within that function.

Then, lastly you may not quite understand what the DOM is. DOM standards for "Document Object Model" and the term is used to represent the objects in a web page. What you are asking about here is javascript global variable syntax which is separate from the DOM.

Hopefully this won't confuse you, but for the sake of completeness of answer, the one place that global Javascript variables and the DOM may appear to be connected is that in a web browser, global variables are also available on the "window" object. So, in my code example above, you access year as:

function showYear() {
    alert("The year is " + year);
}

or as:

function showYear() {
    alert("The year is " + window.year);
}

Both give the same result in a web browser if year is a global variable.

var year = "2011";

means the scope of year is local to the function it is declared in

declare it outside the functions. Or remove the var keyword, which also makes it global.

Your year-var will need a global scope so you can can access it in other functions, ie you define it outside of the functions. Sth like:

var year;

function setParams() {
    year = "2011";
}

function showYear() {
    alert("The year is " + year);
}

Year is scoped to the function setParams and won't be accessible outside of that function.

You could change the function to

function setParams() {
 year = "2011";
}

which would give global access to the year variable

Not necessarily best practise though

Take a look at the module pattern by Douglas Crockford for a useful way to manage global variables and functions:

http://yuiblog.com/blog/2007/06/12/module-pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM