爲未定義我有下面的代碼有問題:對象屬性顯示的console.log
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);
}
);
});
對象鍵不應以數字開頭。 – 2012-08-16 20:54:33
@LoïsDiQual:爲什麼? – 2012-08-16 20:59:52
你有沒有試過'uid.trim()?'遠射,但你永遠不會知道...... – 2012-08-16 21:03:04