为什么没有影响这段JavaScript代码?

时间:2014-10-06 15:07:40

标签: javascript

我读了一本JavaScript书,它为你提供了一段代码,但是当我这样做时,我什么也得不到。它运行但没有显示任何内容。

var theNumber = Number(prompt("Pick a number", ""));
alert("Your number is the square root of " +
  theNumber * theNumber);

我在Harp项目中运行这段代码,其中_layout.jade看起来像:

doctype
html
  head
    link(rel="stylesheet" href="/main.css")
  body
    != yield
    <script src="main.js" type="text/javascript"></script>

main.js

var theNumber = Number(prompt("Pick a number", ""));
alert("Your number is the square root of " +
  theNumber * theNumber);

我知道配置正常,因为我之前已经运行了另一段代码。谷歌浏览器运行代码,但不显示任何窗口。我认为它可能是adPause,但事实并非如此。任何人都知道它会发生什么? 感谢

1 个答案:

答案 0 :(得分:0)

如果要在chrome中打开.js文件,您只需将其视为原始文本即可。您需要将其包含在html页面中,如下所示:

<html>
    <head>
        <script type='text/javascript'>
            window.onload = function()
            {
                var theNumber = Number(prompt("Pick a number", ""));
                alert("Your number is the square root of " + (theNumber * theNumber));
            }
        </script>
    </head>
    <body>

        <!-- page content, if any -->

    </body>
</html>

- 或 -

<html>
    <head>
        <script type='text/javascript' src='script.js'></script>
    </head>
    <body>

        <!-- page content, if any -->

    </body>
</html>

的script.js:

window.onload = function()
{
    var theNumber = Number(prompt("Pick a number", ""));
    alert("Your number is the square root of " + (theNumber * theNumber));
}