如何访问executeSql函数外的变量

时间:2014-05-20 12:01:31

标签: javascript jquery scope web-sql

如何访问executeSql函数之外的url变量? (评论我想要的地方)

function generateUrl(id, callBack){
    var db = window.openDatabase("Database", "1.0", "Marktplaats", 200000);
    db.transaction(function (tx) {

    tx.executeSql('SELECT * FROM searches, settings', [], function (tx, results) {
         var url = "http://google.nl";
    }, null);

    //I want to access the url variable here
    });
}

1 个答案:

答案 0 :(得分:1)

你建议的内容没有意义,因为executeSql是异步的。

tx.executeSql('SELECT * FROM searches, settings', [], function (tx, results) {
     var url = "http://google.nl";
     // This is executed 2nd
}, null);

//This is executed 1st
});

因此,在您发表评论时,url无法获得价值。

您应该做的是使用callBack参数将url传递给调用者:

tx.executeSql('SELECT * FROM searches, settings', [], function (tx, results) {
     var url = "http://google.nl";
     callBack.call(this, url);
}, null);

然后您可以将generateUrl称为:

generateUrl(15, function(url) {
    // URL is visible now
    console.log(url);
});