2014-03-04 45 views
0

我在.html文件中有以下代碼,然後用瀏覽器打開它。爲什麼在頁面加載時沒有收到「Hello World」警報?我看到的只是「測試」文本。非常簡單的jQuery函數不起作用

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

把你的功能一個額外的腳本標籤。 – Sebsemillia

+0

在此之間添加一個'

2

不能聲明[src]屬性<script>元素的內容執行。

您需要使用第二<script>元素:

<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'); 
}); 
+0

[嗯,這個答案感覺很奇怪](http://stackoverflow.com/a/21488173/497418)。 – zzzzBov

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

用第一個script標籤我們加載jquery。 第二個腳本

0

由於已經提到的一些答案,您不能讓瀏覽器通過一個腳本標記查看src和內容。這裏是關於它的信息W3C

腳本可以SCRIPT元素的內容內,或者在外部文件中定義。如果未設置src屬性,則用戶代理程序 必須將元素的內容解釋爲腳本。如果src 具有URI值,則用戶代理必須忽略該元素的內容,並且通過URI檢索該腳本。

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