JQuery -奇数整数/字符串问题

JQuery - Odd integer/string issue

本文关键字:字符串 问题 整数 JQuery      更新时间:2023-09-26

我已经做了一天了,还没有得到它。我有这段代码来加载和显示一些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);
});

首先,数字id无效。所以不要使用它们。

其次,确保firstLevel.id没有尾随或前导空格..

尝试console.log(id, id.toString().length);,看看length是否确实是3