2011-02-18 84 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> 
相關問題