使用jQuery循环插入HTML5数据库 [英] Inserting into HTML5 database with jQuery loop
问题描述
JavaScript不是我的强项,所以如果这很明显,请原谅.
Javascript is not my forte, so excuse me if this is incredibly obvious.
我正在研究一些代码,这些代码创建本地数据库和表,检索RSS feed,对其进行解析,并将每个条目中的信息添加到数据库中.
I'm working on some code that creates a local database and table, retrieves an RSS feed, parses it, and adds information from each entry to the database.
$.ajax({
type: "GET",
url: feedurl,
dataType: "xml",
success: parseXml
});
function parseXml(xml){
$(xml).find("item").each(function(){
title = $(this).find("title").text();
description = $(this).find("description").text();
postype = $(this).find("postype").text();
category = $(this).find("category").text();
guid = $(this).find("guid").text();
postid = $(this).find("postid").text();
url = $(this).find("enclosure").attr('url');
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Posts (title, description, postype, category, guid, postid) VALUES (?,?,?,?,?,?)', [title, description,postype,category,guid,postid]);
});
return true;
});
}
这是问题.一切正常,直到插入查询.插入查询正在插入数据,但每次迭代都使用相同的数据(RSS提要中的最后一项).如果我在'title'变量之前添加alert()或将变量附加到div,则所有操作都不会出现问题.我不明白.
Here's the issue. Everything is working up to the insert query. The insert query is inserting data but it uses the same data (the last item in the RSS feed) every iteration. If I add alert() right before the 'title' variable or append the variables to a div, it all works without a problem. I don't get it.
帮助!
推荐答案
事务花费一些时间,并且您在声明中缺少了var
关键字,从而共享了一些全局变量.添加var
以便循环迭代,因为它是 own 变量集,应该可以解决此问题:
The transactions take a slight amount of time, and you're sharing some global variables by missing the var
keyword on your declarations. Adding var
so iterations of the loop as it's own variable set should fix the issue:
function parseXml(xml){
$(xml).find("item").each(function(){
var $this = $(this),
title = $this.find("title").text(),
description = $this.find("description").text(),
postype = $this.find("postype").text(),
category = $this.find("category").text(),
guid = $this.find("guid").text(),
postid = $this.find("postid").text(),
url = $this.find("enclosure").attr('url');
db.transaction(function(tx) {
tx.executeSql('INSERT INTO Posts (title, description, postype, category, guid, postid) VALUES (?,?,?,?,?,?)', [title, description,postype,category,guid,postid]);
});
});
}
这篇关于使用jQuery循环插入HTML5数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!