简单的Javascript程序不起作用

时间:2014-10-01 11:40:58

标签: javascript html

所以我是JavaScript的新手,我刚写了一个简单的程序;但是,我不确定它为什么不起作用。我在下面显示了HTML和Javascript代码。

HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <h1>Rectangular Prism Calculator</h1>
        <h2 id="hLength">Length: N/A</h2>
        <h2 id="hWidth">Width: N/A</h2>
        <h2 id="hDepth">Depth: N/A</h2>
        <h2 id="hSurfaceArea">Surface Area: N/A</h2>
        <h2 id="hVolume">Volume: N/A</h2>
        <script src="main.js"></script>
    </body>
</html>

JavaScript的:

var length;
var width;
var depth;

length = 20;
width = 10;
depth = 15;

// Write length to document
var wLength = document.getElementbyId('hLength');
wLength.textContent = "Length: " + length;

// Write width to document
var wWidth = document.getElementbyId('hWidth');
wWidth.textContent = "Width: " + width;

// Write depth to document
var wDepth = document.getElementbyId('hDepth');
wDepth.textContent = "Depth: " + depth;

// Calculate surface area
var calculateSurfaceArea = function(l, w, d) {
    var surfaceArea = 2*l*d + 2*l*w + 2*w*d;
    return surfaceArea;
}

// Write surface area to document
var wSurfaceArea = document.getElementById('hSurfaceArea');
wSurfaceArea.textContent = "Surface Area: " + calculateSurfaceArea(length, width, depth);

// Calculate volume
var calculateVolume = function(l, w, d) {
    var volume = l*w*d;
    return volume;
}

// Write volume to document
var wVolume = document.getElementById('hVolume');
wVolume.textContent = "Volume: " + calculateVolume(length, width, depth);

为了验证,我确保HTML文档的名称是'index.html',JavaScript文档名为'main.js'

非常感谢, Malleekk

2 个答案:

答案 0 :(得分:4)

您的代码中有拼写错误:

getElementbyId 

应该是:

getElementById

Working Demo of your corrected code

你应该学习how to debug your Javascript code。与Firefox中的Firefox /开发者工具中的Firebug相处。

答案 1 :(得分:2)

Javascript区分大小写,通常函数的名称都有驼峰式样,所以这是错误的:

... document.getElementbyId ...

替换为

... document.getElementById ...