简体   繁体   中英

Javascript not working in external file

I'm trying some JS basics for a little test and have encountered with a problem when trying to put the Javascript code outside of the HTML one.

The HTML:

<body id="index" class="home">
<table style="width:100%">
<thead>
<tr>
    <th>Region</th>
    <th>Population 2012</th>
    <th>Population 2035</th>
    <th>Annual Growth</th>
    <th>Daily Growth</th>
    <th>Incr./Sec</th>
    <th>Live Pop</th>
    <th>GDP p/c annual</th>
    <th>GDP p/c month</th>
    <th>Incr./Sec</th>
    <th>GDP 2012</th>
    <th>GDP 2013</th>
    <th>Area</th>
    <th>Land</th>
    <th>Water</th>
    <th>Density</th>
</tr>
</thead>
<tr>
<th>EU</th>
<td>503 492 041</td>
<td>520 654 000</td>
<td>746 172</td>
<td>2 044</td>
<td>0.02366</td>
<td><label id="populationEU">503604514.99676</label></td>
<td>31 959.42 €</td>
<td>2 663.29 €</td>
<td><label id="GDPEUIncrement">0.00101</label> €</td>
<td>16 091 315 618 944.38 €</td>
<td><label id="GDPEU">2 425 518 867 456.69</label> €</td>
<td>4 324 782.00 km<sup>2</sup></td>
<td>4 191 578.71 km<sup>2</sup></td>
<td>133 203.29 km<sup>2</sup></td>
<td>116.42 hab/ km<sup>2</sup></td>
</tr>
<h1 id="test"></h1>
<hr />
<tr>
<th>Asia</th>
<td>4 227 067 000</td>
<td>6 534 959 649</td>
<td>84 541 340</td>
<td>231 620</td>
<td><label id="populationAsiaIncrement">2.6808</label></td>
<td><label id="populationAsia">4239810309.5035</label></td>
<td>4 629.42 €</td>
<td>385.79 €</td>
<td><label id="GDPAsiaIncrement">0.00016</label> €</td>
<td>19 568 885 419 408.00 €</td>
<td><label id="GDPAsia">3 120 792 273 016.10</label> €</td>
<td>44 579 000.00 km<sup>2</sup></td>
<td>43 286 209.00 km<sup>2</sup></td>
<td>1 292 791.00 km<sup>2</sup></td>
<td>94.82 hab/ km<sup>2</sup></td>
</tr>
</table>
<script type="text/javascript" src="js/counters.js"></script>
</body>

And the JS:

var test = document.getElementById("test"); // Test placeholder

var millennium =new Date(2013, 0, 1); //Month is 0-11 in JavaScript
var today=new Date();
var one_day=60*60*24; //Get 1 day in seconds

//Calculate difference btw the two dates, and convert to days
var secondsSinceNewYear = Math.ceil(today.getTime()-millennium.getTime());

var populationEU = document.getElementById("populationEU");
var totalPopEU = 0;
var incrementEU = 1/2 ;

setInterval(popGrowthEU, 500);

function popGrowthEU()
{
totalPopEU = totalPopEU+incrementEU;
populationEU.innerHTML = addCommas(Math.round(totalPopEU*100)/100);
}

var GDPEU = document.getElementById("GDPEU");
var totalGDPEU = 0;
var incrementGDPEU = 1*totalPopEU/10;

setInterval(GDPGrowthEU, 100);

    function GDPGrowthEU()
    {
        totalGDPEU = totalGDPEU+incrementGDPEU;
        GDPEU.innerHTML = addCommas(Math.round(totalGDPEU*100)/100);
    }

var populationAsia = document.getElementById("populationAsia");
var incrementPopAsia = parseFloat(document.getElementById("populationAsiaIncrement").innerHTML);
var totalPopAsia = populationAsia.innerHTML+(incrementPopAsia*secondsSinceNewYear);
var incrementPopAsia = incrementPopAsia/2;
setInterval(popGrowthAsia, 500);

function popGrowthAsia()
    {
        totalPopAsia = totalPopAsia+incrementPopAsia;
        populationAsia.innerHTML = addCommas(Math.round(totalPopAsia*100)/100);
    }

var GDPAsia = document.getElementById("GDPAsia");
var incrementGDPAsia = document.getElementById("GDPAsiaIncrement").innerHTML;
var totalGDPAsia = incrementGDPAsia*secondsSinceNewYear*totalPopAsia;
var incrementGDPAsia = incrementGDPAsia*totalPopAsia/10;

setInterval(GDPGrowthAsia, 100);

function GDPGrowthAsia()
{
totalGDPAsia = totalGDPAsia+incrementGDPAsia;
GDPAsia.innerHTML = addCommas(Math.round(totalGDPAsia*100)/100);
}

function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ' ' + '$2');
}
return x1 + x2;
}

http://jsfiddle.net/9GTFS/

I have some data, for now the initial data it's hardcoded, and though i try to update certain fields (the ones with a "label" tag and id) in certain intervals using JS. When i do It putting the JS code in the HTML page, it works perfectly fine, but when I take it out and put it in a separate file it doesn't work. Actually, i managed to figure out that the line

var incrementPopAsia = parseFloat(document.getElementById("populationAsiaIncrement").innerHTML);

finds the problem that the label with that information (id 'populationAsiaIncrement') returns an "undefined" state and I'm stuck there, because I think everything's right. What could be causing this issue? I think it's not a DOM issue because the JS is loaded at the very end of the page, so every bit of code has been loaded (and so all the DOM elements the javascript needs) and, in fact, the element that's failing (label id="populationAsiaIncrement") actually exists.

The specific problem that ends up showing is that document.getElementById("populationAsiaIncrement").innerHTML for some reason doesn't get assigned to the variable. If I execute just that in Firebug, it shows me the expected value, but when I try to assign it to a variable it gets "undefined".

Put the <script> tag with which you import your JavaScript at the very end of the <body> instead of in the <head> .

Imported scripts are evaluated as soon as the browser gets them, synchronously. If you put a script in the <head> and it tries to find DOM elements, they won't exist because the body of the document hasn't been parsed yet. By putting the script at the end, you avoid that problem.

edit — in your jsfiddle, the code works because that site by default wraps your JavaScript code up inside a function that's set up as a "load" handler for the page. It won't run until after the page has loaded. That's another option for you too, but you'll have to structure the code that way yourself.

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