次のコードに問題があります。
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);
}
);
});