JavaScript;如何声明全局变量?

发布于 2024-10-16 19:24:09 字数 370 浏览 6 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

墨小沫ゞ 2024-10-23 19:24:09

您已在函数范围内声明了 qq 。一旦该功能退出,qq就不再存在。

如果你想有 qq 的提醒,需要在函数外声明。请记住,它仅包含分配给它的最后一个值。

var qq;

$('li').each(function(index) {
    qq=$(this).text();
    alert(index + ': ' + qq);
  });

alert(qq); // Will alert 'bar'

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.

var qq;

$('li').each(function(index) {
    qq=$(this).text();
    alert(index + ': ' + qq);
  });

alert(qq); // Will alert 'bar'
凤舞天涯 2024-10-23 19:24:09

布兰登的回答正确地解释了原因。相反,如果您想知道如何在调用each()之后使其可访问,您可能需要这样的东西:

var qq;

$('li').each(function(index) {
    qq = $(this).text();

    alert(index + ': ' + qq);
  });


alert(qq);

这使得 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:

var qq;

$('li').each(function(index) {
    qq = $(this).text();

    alert(index + ': ' + qq);
  });


alert(qq);

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).

樱娆 2024-10-23 19:24:09

它应该像这样重写:

<script>
var qq;
$('li').each(function(index) {
qq=$(this).text();
alert(index + ': ' + qq);
});
alert(qq);

;

请注意,qq 将仅包含最后一个值,因为每次循环 li 时都会重新分配它。

它不起作用,因为您在匿名函数内声明了 qq 变量,因此它不存在于匿名函数之外。

It should be rewritten like this:

<script>
var qq;
$('li').each(function(index) {
qq=$(this).text();
alert(index + ': ' + qq);
});
alert(qq);

;

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文