/
<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
3 Answers
Reset to default 15You'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.