我不得不承認,我還沒有完全理解JS中的作用域和綁定。所以請忍受我。 我想從函數q1中得到結果r。但是我無法將它傳遞到tx.executeSql調用中的匿名函數之外。 第一個console.log顯示r包含所需的值。但如何將它傳遞給調用函數? 該框架是mootools。javascript中的綁定和作用域
var q1 = function(table, column, where) {
sql = "SELECT " + column + " from " + table;
r = "";
if (where != undefined)
sql += " WHERE " + where;
db.transaction(function(tx) {
tx.executeSql(sql, [], function(tx, results) {
r = results.rows.item(0)[column] ;
console.log(r + " 1 "); //1
}, errorHandler);
});
console.log(r + " 2 "); //2
return r;
}
window.addEvent('domready', function() {
db.transaction(function (tx) {
tx.executeSql('DROP TABLE IF EXISTS nutzer');
tx.executeSql("CREATE TABLE IF NOT EXISTS nutzer ("
+ " id integer not null primary key, "
+ " name text not null default '(unbekannt)', "
+ " jahre integer not null default 0, "
+ " gewicht integer not null default 0)"
);
var params = [1,'der Name',10,30];
tx.executeSql("INSERT OR IGNORE INTO nutzer (id,name,jahre,gewicht) values (?,?,?,?)", params);
});
console.log(q1('nutzer', 'name') + " 3 "); //3
})
控制檯輸出爲:
2
3
der Name 1
歡迎來到** async **的美妙世界!你需要使用回調。 – SLaks
您無法將其退回。你必須讓函數接受一個回調,它將把結果傳遞給它。 –