开发者

How to insert table row if and only if first cell value of a row is not equals to first cell value of next row?

开发者 https://www.devze.com 2023-03-22 04:49 出处:网络
<table> <tr> <td>aaa</td> <td>111</td> </tr> <tr> <td>aaa</td>
             <table>
                <tr>
                   <td>aaa</td>
                   <td>111</td>
                </tr>
                <tr>
                   <td>aaa</td>
                   <td>222</td>
                </tr>
                <tr>
                   <td>bbb</td>
                   <td>111</td>
                </tr>
                <tr>
  开发者_开发知识库                 <td>bbb</td>
                   <td>222</td>
                </tr>
             </table>

In this example second row first cell value 'aaa' and third row first cell value 'bbb' are not same. Now How to add a new table row between second row and third row.


You can use $() to create elements from markup, and insertBefore() to add them before a specific element:

$("tr").each(function() {
    var $prev = $(this).prev("tr");
    if ($prev.length
        && $("td:first", $prev).text() != $("td:first", this).text()) {
        $("<tr><td>New</td><td>Row</td></tr>").insertBefore(this);
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消