2012-02-16 139 views
2

誰能告訴我,爲什麼我總是收到「displaymessage沒有定義」與此代碼錯誤信息。在此先感謝:)爲什麼我總是收到「displaymessage is not defined」的錯誤信息?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>TEST PAGE</title> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 

function displaymessage() { 
    alert("Hello World!"); 
    } 

}); 
</script> 
</head> 

<body> 
<p><input type="button" name="start" id="start" value="start" onclick="displaymessage()" /></p> 
</body> 
</html> 

回答

1

你定義在DOM準備好你的回調函數displayMessage - 這意味着當......好了DOM就緒時,它會被定義。然而 - 你把它作爲一個處理器添加到一個DOM元素的點擊 - 將在之前處理該函數實際上被定義。

將定義移出$(document).ready(function(){...},您就可以。

此外,處理程序綁定到各種DOM事件的首選方式是編程式的,而不是聲明式的。不是增加一個onclick屬性的按鈕,你應該重寫整個事情是這樣的:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 

... 

<script type="text/javascript"> 
$(document).ready(function() { 

function displaymessage() { 
    alert("Hello World!"); 
} 

$('#start').on('click', displaymessage); 

}); 
</script> 
</head> 

<body> 
<p><input type="button" name="start" id="start" value="start"/></p> 
</body> 
</html> 
+0

太好了 - 工作:將定義移出$(document).ready(function(){...} ..謝謝;) – MWD 2012-02-16 02:45:11

2

範圍。你的函數在onload函數的範圍內聲明,所以這是唯一你可以訪問它的地方。要從其他地方訪問它,請將其移到$(document).ready函數之外。

0

你爲什麼要在文檔就緒函數中寫入內容。只要寫外面應該喜歡這個

<script type="text/javascript"> 

function displaymessage() { 
    alert("Hello World!"); 
    } 


</script> 
+0

我將使用將有jQuery的在它的實際腳本。示例: 函數removeAjaxSpinnerFunction(){ $(「#AjaxSpinner」)。remove(); } – MWD 2012-02-16 02:33:32

相關問題