JavaScript增量不起作用 [英] Javascript increment not working

查看:101
本文介绍了JavaScript增量不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这会是一个很好的头衔,因为这是一个最特殊的情况,或者我是非常愚蠢的。

这就是我试图做的事情。

创建一个简单的< meter> 标签,它是HTML5中的新标签。主要问题是与我的JavaScript。我试图增加米标记的价值逐渐在我的JavaScript。但不知何故,它不会按我想要的方式工作。



JavaScript。

  var a = document.getElementById(mtr1); 
setTimeout(function(){
console.log(i);
a.value = i;
},250);
}

我试图每250毫秒逐步增加电表的值。这不会发生。而是米直跳到10。

有趣的是我在控制台中得到的 i 的价值。我得到了 10 的实例,而不是1,2,3 ... 10。



为什么会发生这种情况?

FIDDLE

解决方案

这是一个JavaScript闭包的经典。这里 i 是对变量的实际引用,而不是其副本。在遍历循环后,它的值为10,这就是为什么所有日志调用都写入10日志。

这应该更好:

  for(var i = 0; i< = 10; i ++){
var a = document.getElementById(mtr1);
setTimeout(function(i){
return function(){
console.log(i);
a.value = i;
};
}(i),250 * i);

这里最内层的 i setTimeout 的回调参数,而不是您在循环体中声明的变量。


Well I did not know what exactly would be a good title for this because it is a most peculiar situation or I'm abnormally dumb.

Here's what im trying to do.

Create a simple <meter> tag which is new in HTML5. The main issue is with my javascript. Im trying to increment the value of the meter tag gradually in my javascript. But somehow it doesn't work the way i want.

JavaScript.

for (var i = 0; i <= 10; i++) {
    var a = document.getElementById("mtr1");
    setTimeout(function () {
        console.log(i);
        a.value = i;
    }, 250);
}

I'm trying to increase the value of the meter gradually every 250 ms.This doesn't happen. Instead the meter jumps straight to 10.

What interested me was the value of i that i got in the console. I got instances of 10, instead of 1,2,3...10.

Why does this happen?

FIDDLE

解决方案

It's a JavaScript closures' classic. Here i is an actual reference to the variable, not its copy. After you've iterated through the loop it has the value of 10, that's why all log invocations write 10 to log.
This should work better:

for (var i = 0; i <= 10; i++) {
    var a = document.getElementById("mtr1");
    setTimeout(function (i) {
        return function() {
            console.log(i);
            a.value = i;
        };
    }(i), 250 * i);
}

Here the most inner i is the setTimeout's callback argument, not the variable which you've declared in the loop body.

这篇关于JavaScript增量不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆