2012-01-02 119 views
3

我有一個外部test.js與代碼文件:與外部JS警報消息文件

$(document).ready(function() { 
    alert("I am an alert box2!"); 
}); 


function show_alert() 
{ 
    alert("hihi"); 
} 

在我的.html,我已經包括test.js,jQuery的文件,並有一個按鈕。當點擊它時,show_alert()函數將被調用並且工作。但是,消息「我是一個警告框2!」沒有被解僱。
此外,如果我把我的.html中的document.ready函數與<script>... </script>。有用。我的代碼有什麼問題?外部文件不支持?

回答

7

下列之一:

  1. 你已經在你的腦袋的jquery.js之前包括test.js。
  2. 您有一個錯誤,它在到達就緒函數之前停止您的JavaScript。
+1

你是對的,我在jquery.js之前包含了test.js,thx – red23jordan 2012-01-02 15:00:03

1

您可以在test.js中保留函數testAlert。但是,document.ready應該在腳本標籤之間。

function testAlert(){ 
alert("I am an alert box2!"); 
} 

上面的函數可以在test.js中。

$(document).ready(testAlert);應該在當前頁面的腳本標記中檢查DOM的可用性。

NOTE:事實上,上面是不是強制性的,但寫的jQuery理想的方式,因爲它有助於輕鬆地調試:)

2

它爲我,

下面的代碼:

function show_alert() 
{ 
    alert("hihi"); 
} 

$(document).ready(function() { 
    alert("I am an alert box2!"); 

    $('.button').click(function() { 
     show_alert(); 
    }); 
}); 

認沽jQuery.min.js在HTML代碼中的test.js之前。

+0

http://jsfiddle.net/7r8NM/這裏測試。 – 2012-01-02 15:08:28