0

我正在学习一点 HMTL5 以准备 70-480 考试。我正在尝试做一些javascript代码。它看起来像这样:

function inchestometers(inches) {
    if (inches < 0)
        return -1;
    else {
        var meters = inches / 39.37;
        return meters;
    }
}

var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);


var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";

我有这样的html代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Htnl 5 test</title>
    <script src="script/test.js"></script>

</head>

<body>

<p id="hello">Hello</p>

</body>
</html>

在我的 VS 2012 中,我使用了 Asp.net Empty Web 应用程序项目并添加了 Js 文件和 html 文件。问题是该函数运行正常,没有任何异常。这个函数取自这里: http: //msdn.microsoft.com/en-us/library/cte3c772 (v=vs.94).aspx

但是当我试图运行代码时,我正在获取文档元素,它与主题中的错误一样崩溃。我调查的是 hello 获取空值。我还尝试了从这里获取的代码:

http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.

What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.

Regards Rafal

4

1 回答 1

1

you are getting a problem because your javascript code is running before the element

<p id="hello">

is defined.

the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.

another solution would be to place the code inside two functions like this

function do_conversion() {
    var inches = 12;
    var meters = inchestometers(inches);
    document.write("the value in meters is " + meters);
}
function say_hello() {
    var hello = document.getElementById("hello");
    hello.firstChild.nodeValue = "Hello World";
}

then change the body section like this

<body onload='say_hello()'>
    <script>
      do_conversion();
    </script>

    <p id="hello">Hello</p>

</body>
于 2013-04-27T10:33:21.457 回答