问题描述
这是我的HTML/JavaScript:
Here is my HTML/JavaScript:
<!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>Untitled Document</title>
<script type="text/javascript" src="/script/jquery.js"></script>
<script type="text/javascript">
$(function(){
var $str = "hello world";
function foo() {
alert($str);
}
});
</script>
</head>
<body>
<form name="statusUpdateForm" method="post">
<input type="button" name="submitButton" value=" " onclick="foo();" />
</form>
</body>
</html>
单击按钮时,出现一个JavaScript错误,指出未定义foo.如何调用在document.ready()内部声明的JavaScript函数?
When I click the button, I get a JavaScript error stating that foo is not defined. How can I call a JavaScript function declared inside document.ready()??
推荐答案
基本上,您要将函数的作用域放在另一个函数中.
You're placing the function's scope within another function, basically.
图片:
<script>
document.onload = function(){
function foo(){
alert('bar');
}
};
foo();
</script>
这是您要完成的任务的传真.就像在函数中定义的变量超出其范围之外,函数名称具有相同的特征.
That is the facsimile of what you're trying to accomplish. Just like variables defined within a function are off limits outside of it, function names take on the same characteristics.
侧注 JavaScript不需要在变量名上加上$前缀(尽管就名称而言是可以接受的).我不知道您是否来自PHP,并且已经习惯或意识到了.
Side-Note JavaScript doesn't require $ prefix on variable names (though is acceptable as far as names are concerned). I didn't know if you're coming from PHP and are just accustomed or were aware.
我想将我的评论作为答案.
这篇关于为什么在调用document.ready()中声明的函数时未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!