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

How to compare td with td in previous row

本文关键字:td 一行 比较      更新时间:2023-09-26

我要做的是循环遍历表的每一行,并将每一行的第一个单元格与前一行的第1个单元格进行比较。看起来应该很简单,我相信是的,但现在,我迷失了方向。。这是我的。。我想我已经很接近了,但不太明白我错在哪里了。

$("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();
});

您需要将变量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();
});