【问题标题】:The simplest JavaScript in the world won't work!世界上最简单的 JavaScript 行不通!
【发布时间】:2010-10-24 20:47:37
【问题描述】:

我在单独的 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!”未打印在页面上。我应该怎么做才能完成这项工作?如果可能的话,我不希望将脚本标签移到头部。谢谢。

【问题讨论】:

  • 在哪个浏览器中?这就是 1990 年代遗留脚本的问题。
  • 从脚本标签中删除 src 并放入一个新的。

标签: javascript


【解决方案1】:

我认为 src 标签会覆盖里面的任何东西。

尝试以下方法:

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

【讨论】:

  • 好吧,用任何脚本替换JavaScript/Sample.js,然后用函数替换MyPrint(...)调用。
  • 我认为不需要type属性。
  • @Sime Vidas,在 html5 上不需要
  • @Sinan 好的,需要验证。我的意思是为了让 JavaScript 在当今的浏览器中正确执行不需要它(不管使用的 DOCTYPE)
  • @Sinan 几乎所有浏览器都会忽略 type 属性
【解决方案2】:

您的脚本可以被认为是在 结束 &lt;/script&gt; 元素之后加载的。这应该有效:

<!-- 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>

【讨论】:

    【解决方案3】:
    <script type="text/javascript">
    MyPrint("Hello silly world!");
    </script>
    

    【讨论】:

      【解决方案4】:
      window.onload = function(){
       MyPrint("Hello silly world!");
      };
      

      【讨论】:

      • 脚本使用document.write,所以这不会有想要的行为。
      猜你喜欢
      • 2012-06-27
      • 2022-01-27
      • 1970-01-01
      • 2015-11-24
      • 2018-01-03
      • 1970-01-01
      • 2023-02-02
      • 1970-01-01
      • 2019-01-30
      相关资源
      最近更新 更多