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

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

问题描述

我正在试图解决这个问题,但似乎无法自己解决...

我正在使用Web SQL DB而且我无法使用循环来正常工作它。

我使用:

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

我只得到5 ..我没有得到增量i值。

任何人都可以建议我做错了什么,我应该考虑什么?

解决方案

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

您可以解决($ var $ = $; $< = numberofArticles-1; i ++){

$ b

  function(value){
db.transaction(function(tx){
tx.executeSql('INSERT INTO LOGS(articleID)VALUES(?)',[value]);
}) ;
}(i); //< - 调用函数
};


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]);
  });
 };

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?

解决方案

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天全站免登陆