2011-11-04 76 views
2

我一直在努力研究這一整天,還沒有得到它。我有這樣的代碼來加載和顯示一些JSON數據:JQuery - 奇數整數/字符串問題

var id = firstLevel.id; 
$.each(thirdLevel, function(index4, fourthLevel) { 
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>M "+fourthLevel.male+"</td>"); 
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>H "+fourthLevel.herm+"</td>"); 
    currentRow++; 
    console.log(id); 
}); 

它應該使用表的ID插入新列到行(我有很多不同ID的每一個表),但「 ID」變量似乎並沒有被正確的工作,而我在打印到控制檯,它具有正確的值(421在第一次迭代)

現在,如果我這樣做:

var id = 421; 
$.each(thirdLevel, function(index4, fourthLevel) { 
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>M "+fourthLevel.male+"</td>"); 
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>H "+fourthLevel.herm+"</td>"); 
    currentRow++; 
    console.log(id); 
}); 

它將工作,並將所有新列插入ID爲421的桌子上...

那麼,我的代碼有什麼問題嗎? 非常感謝!

+0

定義「不工作的權利」。 –

+1

你在做什麼「男性」和「herm」都是選擇?大聲笑 – Jason

+0

會很高興知道什麼firstLevel是 –

回答

1

編輯:正如ZenMaster在評論中指出的那樣,因爲你沒有使用id作爲數字,這絕對不是問題。

很有可能您要取出的數據確實是一個字符串,您需要顯示您的JSON的樣子。 如果是這樣的話,您需要使用 parseInt函數來告訴javascript將字符串解析爲一個整數。

var id = parseInt(firstLevel.id); 
$.each(thirdLevel, function(index4, fourthLevel) { 
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>M "+fourthLevel.male+"</td>"); 
    $('#'+id+' tr:nth-child('+currentRow+')').append("<td>H "+fourthLevel.herm+"</td>"); 
    currentRow++; 
    console.log(id); 
}); 

+0

爲什麼?無論如何它都附加到一個字符串。 – ZenMaster

+0

該死的好點ZenMaster!它不被視爲該功能中任何地方的數字。 –

+0

那麼問題是什麼? console.log(id)在我使用它之前就給了我正確的id,可能還有一個bug:/ – Multitut

1

所有numeric IDs are invalid首先。所以不要使用它們..

其次確保firstLevel.id沒有尾隨或前導空格..

嘗試console.log(id, id.toString().length);,看看length確實是3