我在for循环中有一个变量,即使我已将其设为全局,也无法在外部访问。为什么我无法访问它?变量是" finalVar"这是代码:
$(function(){
var successfullStatements = $("#successfullStatements"),
errors = $("#errors")
html5sql.process(
[{
sql:"SELECT * FROM StarWarsCharacters WHERE name=?;",
data:[Jsonvar]
}],
function(transaction, results, rowsArray){
for(var i = 0; i < rowsArray.length; i++){
//the variable I tried to make global
window.finalVar = rowsArray[i].name;
}
},
function(error, statement){
}
);
});
});
alert(finalVar); //tried checking to see if variable could be accessed
答案 0 :(得分:1)
html5sql.process
是一个异步函数。因此,除非执行传递给finalVar
的函数,否则不会填充html5sql.process
。但是只有在获取results
时才会执行。因此,您可能需要将alert
移动到result
实际填充的位置。
$(function() {
var successfullStatements = $("#successfullStatements"),
errors = $("#errors")
html5sql.process(
[{
sql: "SELECT * FROM StarWarsCharacters WHERE name=?;",
data: [Jsonvar]
}],
function(transaction, results, rowsArray) {
for (var i = 0; i < rowsArray.length; i++) {
//the variable I tried to make global
alert(rowsArray[i].name);
}
},
function(error, statement) {}
);
});
答案 1 :(得分:0)
try this:
html5sql.process(
[{
sql:"SELECT * FROM StarWarsCharacters WHERE name=?;",
data:[Jsonvar],
async:false
}],
function(transaction, results, rowsArray){
for(var i = 0; i < rowsArray.length; i++){
//the variable I tried to make global
window.finalVar = rowsArray[i].name;
}
},
function(error, statement){
}
);
Please note the function is called asynchronously here.so you have to make the function call synchronous by making "async:false". Then you can get the variable's value outside the for loop.