使用Javascript的HTML中的唯一行
作者:互联网
我试图基于第一列的值显示唯一行.我已经从类似的问题中进行了很多尝试.
<table id="test" border="1">
<tr>
<td>test1</td>
<td>test2</td>
<td>test3</td>
</tr>
<tr>
<td>test1</td>
<td>test2</td>
<td>test5</td>
</tr>
<tr>
<td>test6</td>
<td>test2</td>
<td>test5</td>
</tr>
<tr>
<td>test6</td>
<td>test6</td>
<td>test9</td>
</tr>
</table
>
**BEFORE**
test1 test2 test3
test1 test2 test5
test6 test2 test5
test6 test6 test9
**AFTER**
test1 test2 test3
test6 test2 test5
这是我尝试使用类似情况下的代码的尝试
arr = [];
$('#test td').each(function(){
key = "" + $(this).index();
if(arr.indexOf( key ) == 1)
arr.push($.trim($(this).text()));
else
$(this).closest('tr').hide();
alert(arr[]);
});
**RESULT**:
test1 test2 test3
解决方法:
循环每个第一个td,如果尚未将其添加到查找对象,则将其添加到该对象.如果存在,请隐藏当前行.
var found = {};
$('#test td:first-child').each(function(){
var td = $(this);
var value = td.text();
if (found[value])
td.closest('tr').hide();
else
found[value] = true;
});
var found = {};
$('#test td:first-child').each(function(){
var td = $(this);
var value = td.text();
if (found[value])
td.closest('tr').hide();
else
found[value] = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="test" border="1">
<tr>
<td>test1</td>
<td>test2</td>
<td>test3</td>
</tr>
<tr>
<td>test1</td>
<td>test2</td>
<td>test5</td>
</tr>
<tr>
<td>test6</td>
<td>test2</td>
<td>test5</td>
</tr>
<tr>
<td>test6</td>
<td>test6</td>
<td>test9</td>
</tr>
</table>
标签:html-table,javascript 来源: https://codeday.me/bug/20191121/2049133.html