I need to set a variables value within a function, but use it outside of the function. Can this be done?
$(document).ready(function() {
$(window).scroll(function () {
var myVar = something;
});
console.log(myVar);
});
I need to set a variables value within a function, but use it outside of the function. Can this be done?
$(document).ready(function() {
$(window).scroll(function () {
var myVar = something;
});
console.log(myVar);
});
Share
asked Aug 7, 2013 at 15:21
EvanssEvanss
22.8k101 gold badges322 silver badges557 bronze badges
1
-
1
Before your
.scroll
handler, addvar myVar;
. In the.scroll
handler, don't usevar
(which will create a new variable). Note, however, thatmyVar
will be undefined when youlog
it because it's not set until the scroll handler actually runs. – Matt Burland Commented Aug 7, 2013 at 15:23
3 Answers
Reset to default 4Yes, but you need to first declare it outside of the function.
$(document).ready(function() {
var myVar;
$(window).scroll(function () {
myVar = something;
});
console.log(myVar);
});
Just know that myVar
will only be updated after the scroll event is triggered. So, your console.log
will log undefined
because it runs before the event runs and sets the variable.
Yes. Just declare variable outside the function.
<script>
var myVar = "foo";
$(document).ready(function() {
$(window).scroll(function () {
myVar = something;
});
console.log(myVar);
});
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744923106a4601257.html
评论列表(0条)