如何将td与前一行中的td进行比较

时间:2015-12-10 20:56:53

标签: javascript jquery

我要做的是遍历表格的每一行,并将每行的第一个单元格与前一行的第一个单元格进行比较。看起来它应该很简单,我确信它是,但是现在,我迷失了它.. 这就是我所拥有的......我认为我很接近,但不能完全弄清楚我的错误。

$("tr td:first-child").each(function(){
    if(($(this).text()) == lastId){
    console.log("YEP, the same");
    }else{
    console.log("no, different Id");
     } 
     var lastId = $(this).text();
});

1 个答案:

答案 0 :(得分:3)

您需要将变量lastId保留在另一个范围内。这里每次迭代都会丢失。

var lastId;
$("tr td:first-child").each(function(){
    if(($(this).text()) == lastId){
        console.log("YEP, the same");
    }else{
        console.log("no, different Id");
    } 
    lastId = $(this).text();
});