2011-02-18 88 views
3

我想要做一个非常基本的jQuery教程,但我无法让它工作。 我从谷歌调用jquery库,然后尝试在html中创建一个脚本。jquery不能在HTML文件中工作

如果我在.js文件中做同样的事情,我不会有任何问题。 我在这里错过了什么?

<html> 
    <head> 
     <title></title> 
     <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    </head> 
    <body> 
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"> 
      $(document).ready(function() { 
       $("a").click(function() { 
        alert("Hello world!"); 
       }); 
      }); 
     </script> 
      <a href="">Link</a> 

    </body> 
</html> 

回答

10

您需要拆分这件事:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"> 
    $(document).ready(function() { 
     $("a").click(function() { 
      alert("Hello world!"); 
     }); 
    }); 
</script> 

...分成两个脚本元素:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $("a").click(function() { 
      alert("Hello world!"); 
     }); 
    }); 
</script> 

在你给的片段中,<script>元素中的代码获得了”因为浏览器只评估src属性的内容而忽略其他所有内容。

+0

我已经花了东西,所以愚蠢的时间量是疯了。我从未想过它需要2个元素。非常感谢。 – 2011-02-18 07:38:30

1

移动你的脚本到head元素是这样的:

<html> 
<head> 
    <title></title> 
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      $("a").click(function() { 
       alert("Hello world!"); 
      }); 
     }); 
    </script> 
</head> 
<body>  
    <a href="#">Link</a> 
</body> 
</html> 
相关问题