为什么在 document.ready() 中声明的函数在调用时未定义?
这是我的 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 函数?
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>
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()??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
基本上,您将函数的作用域放置在另一个函数中。
想象一下:
这就是您想要实现的目标的复制品。就像函数内定义的变量在函数外部是不受限制的一样,函数名称也具有相同的特征。
旁注 JavaScript 不需要在变量名称上使用 $ 前缀(尽管就名称而言是可以接受的)。我不知道您是否来自 PHP,是否只是习惯或知道。
我想我会把我的评论作为答案。
You're placing the function's scope within another function, basically.
Picture this:
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.
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.
Thought I'd make my comment an answer.
试试这个:
基本上,您需要将函数公开到全局范围。
Try this:
Basically, you need to expose the function to global scope.
$(function() 函数内部声明的变量和方法只能在该函数内部访问。如果您需要在外部使用这些变量和方法,则可以将其放在全局命名空间中,例如
Variables and methods declared inside the $(function() function are only accessible within that. If you need to use those outside, you you make it in the global namespace like
你不能,它是该范围私有的。
You can not, it is private to that scope.
我最终所做的 - 我应该首先做的 - 是为提交按钮添加一个点击处理程序:
What I ended up doing - what I should have done in the first place - is adding a click handler for the submit button: