Web SQL 数据库 + Javascript 循环 [英] Web SQL Database + Javascript loop

查看:26
本文介绍了Web SQL 数据库 + Javascript 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决这个问题,但我自己似乎无法解决...
我正在使用 Web SQL DB,但无法使用循环来正常使用它.
我使用:

I'm trying to figure this out but can't seem to on my own...
I'm playing with Web SQL DBs and I can't get a loop to work properly with it.
I use:

for (var i=0; i<=numberofArticles-1; i++){  
    db.transaction(function (tx) {  
    tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)',  [i]);
  });
 };

而且我只得到 5 个 .. 我没有得到增量 i 值.
谁能建议我做错了什么以及我应该考虑什么?

And I get only 5's.. I don't get the incremental i values.
Can anyone suggestion what I'm doing wrong and what I should be thinking about?

推荐答案

看起来这个函数是异步的,当 tx.executeSql 触发时,循环已经完成了循环并且 i 已更改多次.

It looks like the function is asynchronous, and that by the time tx.executeSql fires, the loop have finished looping and i has been changed several times.

你可以用闭包来解决这个问题.

You can solve this with a closure.

for (var i=0; i<=numberofArticles-1; i++){ 
    function (value) { 
        db.transaction(function (tx) {  
        tx.executeSql('INSERT INTO LOGS (articleID) VALUES (?)',  [value]);
      });
    }(i); // <-- CALL the function
 };

这篇关于Web SQL 数据库 + Javascript 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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