代码之家  ›  专栏  ›  技术社区  ›  ZhouW

Javascript-更改document.ready中的全局变量?

  •  -1
  • ZhouW  · 技术社区  · 7 年前

    我有一个全局变量 numberOfMessages

    var numberOfMessages = 0 // declared outside any function, so should be global
    $(document).ready(function () {
    Message.deployed().then(function (contractInstance) {
        contractInstance.getNumberMessages.call().then(function (v) {
          numberOfMessages = v
          alert(numberOfMessages) // returns something other than 0
        })
      })
    })
    alert(numberOfMessages) // returns 0
    

    如何将全局变量设置为加载页面时函数返回的值?

    3 回复  |  直到 7 年前
        1
  •  2
  •   Soviut    7 年前

    .then() 在异步调用完成之前。

    alert() 测试您的代码,因为这样的提示通常是阻塞的,这意味着暂停代码执行,并且可以对异步回调进行奇怪的操作。而是使用 console.log() 并在浏览器的Javascript控制台中查看结果(通常通过点击F12打开)。

        2
  •  -1
  •   chu.tien    7 年前

    尝试删除

    var numberOfMessages = 0
    

        3
  •  -1
  •   CodeMonkey    7 年前

    根据其他几个类似的问题,我可以说将变量声明为 window.numberOfMessages = 0

    #3窗口。a=0;

    引用全局对象的窗口全局(在浏览器上;一些 非浏览器环境具有等效的全局变量,例如

    此属性是可枚举的,在 IE8 我试过的浏览器。

    here 并解释了什么是全局范围变量和全局显式变量。

    window.numberOfMessages = 0 // This creates a property on the global object explicitly
    $(document).ready(function() {
      Message.deployed().then(function(contractInstance) {
        contractInstance.getNumberMessages.call().then(function(v) {
          window.numberOfMessages= v
          console.log(window.numberOfMessages) // returns something other than 0
        })
      })
    })
    console.log(window.numberOfMessages) // returns 0
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>