2012-02-16 141 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

相关问题