1

我有一个示例代码:

<table id="modem_list">
   <tr class="input_1" name="modem">
      <td>iPad 1<input type="hidden" value="1" class="output_1"></td>
   </tr>
   <tr class="input_2" name="modem">
      <td>iPad 2<input type="hidden" value="2" class="output_2"></td>
   </tr>
   <tr class="input_1" name="modem">
      <td>iPad 1<input type="hidden" value="1" class="output_1"></td>
   </tr>
</table>

<input type="button" class="submit" onclick="update()" value="submit" />

和 javascript

function update() {
  var table = document.getElementById("modem_list");
var rowCount = table.rows.length;
for(var i=0; i<rowCount-1; i++) {
    for(var j=i+1; j<rowCount; j++) {
        if(table.rows[i] == table.rows[j]) {
            rowCount--;
            for(var k=j; k<rowCount; k++) {
                table.rows[k] = table.rows[k+1];
                table.deleteRow(k);
                k--;
            }
        }
    }
}
}

如何修复结果是:

<table id="modem_list">
       <tr class="input_1" name="modem">
          <td>iPad 1<input type="hidden" value="1" class="output_1"></td>
       </tr>
       <tr class="input_2" name="modem">
          <td>iPad 2<input type="hidden" value="2" class="output_2"></td>
       </tr>
    </table>
4

1 回答 1

2

假设您想tr根据它们的类删除重复的元素,您可以试试这个:

function update() {
    //caches a reference to which table we're working with
    var table = document.getElementById("modem_list");
    //gets all its rows
    var trs = table.rows;

    //iterates through all rows
    for (var i=0; i<trs.length; i++) {
        //stores possible dupes in an array
        var dupes = table.getElementsByClassName(trs[i].className);
        //if there are any dupes.. (more than 1 element with same class)
        if (dupes.length > 1)
            //removes all repeated elements except the first (index 0)
            for (var j=1; j<dupes.length; j++)
                dupes[j].parentNode.removeChild(dupes[j]);
    }
}

JSFiddle

于 2012-06-14T09:02:17.623 回答