我整天都在研究这个,但还没搞定。我有这段代码来加载和显示一些 JSON 数据:
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 的表中...
那么,我的代码有问题吗? 非常感谢!
最佳答案
编辑:正如 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);
});
罢工><罢工>罢工>
关于javascript - JQuery - 奇怪的整数/字符串问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8016249/