JQuery – 奇数整数/字符串问题
我整天都在努力工作,还没有完成。 我有这个代码来加载和显示一些JSON数据:
var id = firstLevel.id; $.each(thirdLevel, function(index4, fourthLevel) { $('#'+id+' tr:nth-child('+currentRow+')').append("M "+fourthLevel.male+" "); $('#'+id+' tr:nth-child('+currentRow+')').append("H "+fourthLevel.herm+" "); currentRow++; console.log(id); });
它应该使用表的id在一行中插入新列(我有很多表,每个表都有不同的ID)但是“id”变量似乎没有正常工作,我将它打印到控制台,它具有正确的值(第一次迭代中为421)
现在,如果我这样做:
var id = 421; $.each(thirdLevel, function(index4, fourthLevel) { $('#'+id+' tr:nth-child('+currentRow+')').append("M "+fourthLevel.male+" "); $('#'+id+' tr:nth-child('+currentRow+')').append("H "+fourthLevel.herm+" "); 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("M "+fourthLevel.male+" "); $('#'+id+' tr:nth-child('+currentRow+')').append("H "+fourthLevel.herm+" "); currentRow++; console.log(id); });
首先, 数字ID无效 。 所以不要使用它们..
其次确保firstLevel.id
没有尾随或前导空格。
试试console.log(id, id.toString().length);
并查看length
是否确实为3