列表表tr中是否存在如何删除值?

时间:2012-06-14 08:16:04

标签: javascript

我有一个示例代码:

<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>

1 个答案:

答案 0 :(得分: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