【问题标题】:Very simple jQuery function is not working [duplicate]非常简单的jQuery函数不起作用[重复]
【发布时间】:2014-03-05 03:49:39
【问题描述】:

我在 .html 文件中有以下代码,然后我用浏览器打开它。为什么我在页面加载时没有收到“Hello World”警报?我看到的只是“测试”文本。

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
            $(document).ready(function() {
            alert("Hello World!");
        });
        </script>
    </head>
    <body>
    <p>
        Test
    </p>
    </body>
</html>

【问题讨论】:

  • 把你的函数放在一个额外的脚本标签中。
  • 在这之间添加一个&lt;script type="text/javascript"&gt;&lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;$(document)
  • 哈哈哈,我见过的最好的复制品!

标签: jquery html


【解决方案1】:

您不能声明[src] 属性并且执行&lt;script&gt; 元素的内容。

您需要使用第二个&lt;script&gt; 元素:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        alert("Hello World!");
    });
</script>

注意:在 jQuery 中使用 document.ready 回调时,建议使用简写版本将 jQuery 别名为 $ 以获得更好的脚本兼容性:

jQuery(function ($) {
    alert('Hello World');
});
【解决方案2】:

改成这样

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
      <script>
        $(document).ready(function() {
        alert("Hello World!");
    });
    </script>

【讨论】:

  • 但是为什么这行得通?
【解决方案3】:

正如一些答案已经说明的那样,您不能让浏览器通过一个脚本标签查看src 和内容。这是W3C的相关信息:

脚本可以在 SCRIPT 元素的内容或外部文件中定义。 如果未设置 src 属性,则用户代理 必须将元素的内容解释为脚本。如果源 有一个 URI 值,用户代理必须忽略元素的内容并且 通过 URI 检索脚本。

http://www.w3.org/TR/html401/interact/scripts.html

【讨论】:

    【解决方案4】:
    <!DOCTYPE html>
    <html>
         <head>
             <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
             <script type="text/javascript">           
                    $(document).ready(function() {
                        alert("Hello World!");
                   });
             </script>
         </head>
         <body>
             <p>Test</p>
         </body>
    </html>
    

    使用第一个脚本标签,我们加载 jquery。 在第二个脚本中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-17
      相关资源
      最近更新 更多