简体   繁体   English

Javascript无法在外部文件中工作

[英]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. 我正在尝试一些JS基础知识进行一些测试,并且在尝试将Javascript代码放在HTML之外时遇到了问题。

The HTML: 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: 和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/ 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. 我有一些数据,现在初始数据是硬编码的,虽然我尝试使用JS在某些间隔更新某些字段(带有“label”标签和id的字段)。 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. 当我这样做它将JS代码放在HTML页面中时,它工作得非常好,但当我把它取出并放在一个单独的文件中时它不起作用。 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. 发现带有该信息的标签(id'populationAsiaIncrement')返回“未定义”状态并且我被困在那里的问题,因为我认为一切都是正确的。 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. 我认为这不是一个DOM问题,因为JS是在页面的最后加载的,所以每一段代码都已加载(所以javascript需要的所有DOM元素),实际上,它是失败的元素(标签) id =“populationAsiaIncrement”)确实存在。

The specific problem that ends up showing is that document.getElementById("populationAsiaIncrement").innerHTML for some reason doesn't get assigned to the variable. 最终显示的具体问题是document.getElementById("populationAsiaIncrement").innerHTML由于某种原因, document.getElementById("populationAsiaIncrement").innerHTML没有被赋值给变量。 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". 如果我在Firebug中执行它,它会向我显示预期值,但是当我尝试将其分配给变量时,它会“未定义”。

Put the <script> tag with which you import your JavaScript at the very end of the <body> instead of in the <head> . 将用于导入JavaScript的<script>标记放在<body>的最末端 ,而不是<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. 如果您将脚本放在<head>并尝试查找DOM元素,则它们将不存在,因为尚未解析文档正文。 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. 编辑 - 在您的jsfiddle中,代码可以正常运行,因为该站点默认将JavaScript代码包装在一个设置为页面“加载”处理程序的函数中。 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. 这也是你的另一个选择,但你必须自己构建代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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