【发布时间】: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