gpt4 book ai didi

javascript - 如何删除列表表tr中已经存在的值?

转载 作者:行者123 更新时间:2023-11-30 18:25:15 26 4
gpt4 key购买 nike

我有一个示例代码:

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

最佳答案

假设你想根据它们的类删除重复的 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

关于javascript - 如何删除列表表tr中已经存在的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11029164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com