在HTML表格中查找重复的数据 [英] Find duplicated data in a HTML table

查看:291
本文介绍了在HTML表格中查找重复的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML中有一个表格,在这个表格中,< td> 标签中的各个值是从一个Javascript数组中生成的。

b
$ b

我想比较< td> 标签中包含的值,并检查是否有重复。

解决方案

< td> 元素没有,他们有内容(可能包含或不包含其他元素)。如果您的问题是如何检查没有两个td元素具有相同的内容?你可以做这样的事情:

  var contents = {},
duplicates = false;
$(#yourtableidhere td)。each(function(){
var tdContent = $(this).text();
if(contents [tdContent]){
duplicates = true;
return false;
}
contents [tdContent] = true;
});
if(重复)
alert(有重复项。);

您不会说这个过程何时应该发生,但是如果回应用户点击一个按钮或者其他东西,然后把上面的代码放到一个点击事件处理程序中。



演示: http://jsfiddle.net/FA6SR/



显然,您可以展开上述内容来确切指出哪些单元格有重复值,等等。

编辑 - PS 您提到这些值来自数组。对数组进行比较测试,而不是针对表格单元,而是在运行时更高效。 jQuery对此无能为力,您只需使用标准循环。


I have a table in my HTML, and in this table the individual values within the <td> tags are generated from an Javascript array.

I want to compare the values contained in the <td> tags against each other and check for duplicates.

解决方案

<td> elements don't have a value, they have contents (that may or may not include other elements). If your question is "How do I check that no two td elements have the same contents?" you can do something like this:

var contents = {},
    duplicates = false;
$("#yourtableidhere td").each(function() {
    var tdContent = $(this).text();
    if (contents[tdContent]) {
        duplicates = true;
        return false;
    }
    contents[tdContent] = true;
});    
if (duplicates)
   alert("There were duplicates.");

You don't say when this process should occur, but if in response to the user clicking a button or something then put the above code in a click event handler.

Demo: http://jsfiddle.net/FA6SR/

Obviously you can expand the above to note exactly which cells had duplicate values, what the values were, etc.

EDIT - P.S. You mention that the values come from an array. It would be just as easy to code the comparison test against the array rather than against the table cells, but more efficient at runtime. jQuery wouldn't really help with that, you'd just use a standard for loop.

这篇关于在HTML表格中查找重复的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆