世界上最简单的JavaScript也无法工作!

3

我有一个单独的Sample.js文件,其中包含以下脚本:

function MyPrint(text)
{
 document.write(text);
}

我有以下HTML页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Silly example</title>
</head>
<body>
    <div>
        <script type="text/javascript" src="JavaScript/Sample.js">
            MyPrint("Hello silly world!");
        </script>
    </div>
</body>
</html>

最终结果是页面上没有打印出文本“Hello silly world!”。我该怎么做才能让它起作用?如果可能的话,我希望不移动脚本标签到头部。谢谢。

在哪个浏览器?这就是这些上世纪90年代遗留的脚本问题。 - Manius
3
将脚本标签中的“src”移除并替换为一个新的。 - Shawn Mclean
4个回答

18

我认为src标签会覆盖内部的内容。

尝试以下操作:

    <script type="text/javascript" src="JavaScript/Sample.js"></script>
    <script type="text/javascript">
        MyPrint("Hello silly world!");
    </script>

好的,请将“JavaScript/Sample.js”替换为脚本名称,然后将“MyPrint(...)”调用替换为该函数。 - Tim Čas
我认为不需要type属性。 - Šime Vidas
@Sime Vidas,这在HTML5上不需要。 - Sinan
@Sinan,这是必要的验证。我的意思是,无论使用哪种DOCTYPE,今天的浏览器都可以正确执行JavaScript,因此它不是必需的。 - Šime Vidas
我认为保留类型是一个好的实践。这只是我的个人意见。 - Tim Čas
显示剩余3条评论

4

只有在闭合的</script>标签后,您的脚本才能被视为已加载。以下方法可行:

<!-- just a sidenote: type="text/javascript" is the default for script as of html5 -->
<script src="JavaScript/Sample.js"></script>
<script>MyPrint("Hello silly world!");</script>

0
<script type="text/javascript">
MyPrint("Hello silly world!");
</script>

-1
window.onload = function(){
 MyPrint("Hello silly world!");
};

2
该脚本使用了document.write,因此它将无法产生预期的行为。 - Quentin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接