javascript选择td´s并计数重复项

javascript select td´s and count duplicates

本文关键字:td 选择 #180 javascript      更新时间:2024-05-24

您可以看到下面的代码,我正试图从表中选择第三个td来计数重复项。

我想把它们保存在一个新数组中,并使用新数组来迭代和查找重复项。

我试着如下选择想要的td。Firefox给了我td<sport>标签所在的所有项目,但IE只给了我一个运动标签。请注意,代码位于表之后

function doIt()
{   
var table = document.getElementById('table');
var tr = table.getElementsByTagName('tr');
content = new Array;
for (var i=0; i<tr.length; i++)
{
content = tr[i].getElementsByTagName('td')[2].innerHTML;
document.write(content);
}
}
<tr class="grey">
  <td><Date>25.09.2014</Date></td>
  <td><Time>09:00:00</Time></td>
  <td><Sport>Soccer, Tennis</Sport></td>
</tr>
<tr class="blue">
  <td><Date>25.09.2014</Date></td>
  <td><Time>09:45:00</Time></td>
  <td><Sport>Basketball, Volleyball</Sport></td>
</tr>
<tr class="grey">
  <td><Date>25.09.2014</Date></td>
  <td><Time>10:00:00</Time></td>
  <td><Sport>Soccer, Tennis</Sport></td>
</tr>...

我希望我理解你想要什么。这是一个有效的JS。它查看所有的sport标记,只添加那些没有的标记JSFiddle此处

// Initialize empty array    
var array = [];
// Get all the sport tags
var sportTags = document.getElementsByTagName('sport');
// Iterate over the sport tags
for(var i = 0; i < sportTags.length; i++){
    // Get the inner HTML
    var current = sportTags[i].innerHTML;
    // If it does not already exist, add it to the array
    if (array.indexOf(current) < 0) {
        array.push(current);
    }
}
// Print the array to check the results
alert(array);