我对以下代码有疑问:
var data = {};
$('table tr').each(function() {
var uid = $('td a', $(this)).attr('href').split('=')[1];
TTDB.transaction(
function (tx) {
tx.executeSql("SELECT id FROM players WHERE uid = ?;", [uid], function (txSub, results) {
data[uid] = results.rows.item(0).id;
}, TTDBerrorHandler);
}
);
});
$('#member tbody tr').each(function() {
var uid = $('td a', $(this)).attr('href').split('=')[1];
console.log(uid); // Returns correctly 1643 as shown below
console.log(data); // Returns whole object correctly
console.log(data['1643']); // Returns **undefined**
console.log(data[uid]); // Returns **undefined**
console.log(uid); // uid is still correctly set to 1643
/* Following from Safari console
1643
Object
156: 1
217: 17
295: 138
579: 136
764: 139
774: 142
816: 144
826: 14
955: 73
1096: 137
1133: 13
1134: 141
1232: 140
1321: 11
1643: 31
2307: 143
__proto__: Object
undefined
undefined
1643
*/
});
这是一个可以正常工作的测试集。
var test = {};
test[156] = 1;
test[1643] = 31;
var testUid = 1643;
console.log(test);
console.log(test['1643']); // Returns correctly 31 as shown below
console.log(test[testUid]); // Returns correctly 31 as shown below
/* This is from Safari console
Object
156: 1
1643: 31
__proto__: Object
31
31
*/
由于基本相同的测试集工作,我猜这个问题与本地数据库的异步操作有关,但我不知道如何解决这个问题......
更新: 澄清我的问题/我想要实现的目标。
例如,如果我有一个表,我对其进行迭代,然后想要添加一些包含数据库数据的字段。
<table>
<tr><td class="uid">123<td></tr>
<tr><td class="uid">234<td></tr>
</table>
然后我想向它添加新列:
$('table tr').each(function() {
var uid = $('td.uid', $(this)).text();
TTDB.transaction(
function (tx) {
tx.executeSql("SELECT id FROM players WHERE uid = ?;", [uid], function (txSub, results) {
// Problem is that because this transaction is asynchronous $(this) is
// not defined when this gets executed.
$(this).append('<td class="id">' + id + '</td>');
}, TTDBerrorHandler);
}
);
});