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

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

programmeradmin3浏览0评论

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>
发布评论

评论列表(0)

  1. 暂无评论