【问题标题】:Getting the Global Variable to change based on increment defined within an onclick function?让全局变量根据 onclick 函数中定义的增量进行更改?
【发布时间】:2014-10-20 17:35:02
【问题描述】:

只想说,对于开发人员和 IT 专业人士来说,这是一个多么棒的论坛。

我在下面有这段代码。我试图在正在处理计数的函数之外获取计数值。但它不起作用,即使该函数有一个全局变量。 无论如何这可以做到吗?

感谢你们的帮助,非常感谢。

var getcountglobal =0;
var that =this.buttonforitem; //this refers to button created by javascript

that.onclick = function()
{

   getcountglobal++;
   console.log(getcountglobal);// in console when clicking the button it gives 1,2,3,etc

} 
console.log(getcountglobal); // here it gives 0 and not the click number. Why doesn't or cant the variable be changed?

【问题讨论】:

  • 为什么你希望变量在函数运行之前改变?
  • 对不起最后一行的错字,应该是:console.log(getcountglobal);谢谢
  • 嗨 SLaks,我认为单击按钮时变量正在更改?就代码而言,这将如何工作?谢谢
  • 最后一个控制台只写一次:第一次运行并初始化全局变量和点击事件时。
  • 感谢大家的cmets。使用 console.log 代替功能点击正在注册。但我没有看到在函数之外获得该值的方法?

标签: javascript function this return-value counter


【解决方案1】:

原因是,console.log(getcountergloba);无论单击如何都会执行,因为它位于事件处理程序(onclick)之外。一旦有人点击,该变量就会增加并打印正确的数字。但是,当您在事件处理程序之外打印它时,它会在任何事件发生之前执行,当时它的值为 0

【讨论】:

    【解决方案2】:

    正在发生的事情是,在您单击按钮之前,正在调用打印出 0 的 console.log。在为您的按钮分配点击处理程序后,它会立即打印出零。

    【讨论】:

      【解决方案3】:
      that.onclick = function()
      {
      
         getcountglobal++;
         console.log(getcountglobal);// in console when clicking the button it gives 1,2,3,etc
      
         console.log(getcounterglobal);//move this in your click
      
      }
      

      每次点击都会更改变量。问题是当 global 为 0 时,您唯一在页面加载时打印它。

      在你的点击中移动 console.log 否则它只会在 global = 0 时第一次加载页面时运行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-12
        • 2016-03-20
        • 1970-01-01
        相关资源
        最近更新 更多