javascript - JS - Set variables value in function but use variable outside of it? - Stack Overflow

I need to set a variables value within a function, but use it outside of the function. Can this be done

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, add var myVar;. In the .scroll handler, don't use var (which will create a new variable). Note, however, that myVar will be undefined when you log it because it's not set until the scroll handler actually runs. – Matt Burland Commented Aug 7, 2013 at 15:23
Add a ment  | 

3 Answers 3

Reset to default 4

Yes, 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信