最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - JavaScript; How do I declare a variable global? - Stack Overflow

programmeradmin4浏览0评论

/

<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/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>
Share Improve this question edited Feb 9, 2011 at 18:55 borayeris asked Feb 9, 2011 at 18:29 borayerisborayeris 2,6501 gold badge27 silver badges31 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 15

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'

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

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.

发布评论

评论列表(0)

  1. 暂无评论