JavaScript;如何声明全局变量?
http://jsfiddle.net/borayeris/6kvyb/
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$('li').each(function(index) {
var qq=$(this).text();
alert(index + ': ' + qq);
});
alert(qq);// Asking this one.
</script>
http://jsfiddle.net/borayeris/6kvyb/
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$('li').each(function(index) {
var qq=$(this).text();
alert(index + ': ' + qq);
});
alert(qq);// Asking this one.
</script>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已在函数范围内声明了 qq 。一旦该功能退出,qq就不再存在。
如果你想有 qq 的提醒,需要在函数外声明。请记住,它仅包含分配给它的最后一个值。
You've declared qq inside the scope of the function. Once that function exits, qq doesn't exist anymore.
If you want to have an alert for qq, you need to declare it outside of the function. Keep in mind that it will only contain the last value that was assigned to it.
布兰登的回答正确地解释了原因。相反,如果您想知道如何在调用each()之后使其可访问,您可能需要这样的东西:
这使得 qq 成为一个全局范围变量,您为每次传递重新分配它的值环形。在循环结束时,变量将保留分配给它的最后一个值(示例中为 bar )。
Brandon's answer is correct in explaining why. If, instead, you want to know how you could make it accessible after the call to each(), you probably want something like this:
This makes qq a global scope variable, which you're reassigning the value of for each pass through the loop. At the end of the loop the variable will retain the last value assigned to it (bar in your example).
它应该像这样重写:
;
请注意,qq 将仅包含最后一个值,因为每次循环 li 时都会重新分配它。
它不起作用,因为您在匿名函数内声明了 qq 变量,因此它不存在于匿名函数之外。
It should be rewritten like this:
;
Note that qq will only contain the last value since you reassign it each time you loop through the li.
It was not working because you declared the qq variable inside an anonymous function, so it did not exist outside of it.