2012-06-14 42 views
1

我有一個示例代碼:如何刪除值已存在於列表tr中?

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

'如果(row.className == row.className)'這將刪除每一行! – Amberlamps

+0

這是一個很奇怪的循環... – geekchic

+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

+0

非常感謝 –