[英]Read all td values with Javascript
I am trying to get all td
and compare each td
value to a string . 我正在尝试获取所有
td
并将每个td
值与一个字符串进行比较。 but my code only reads the first td
of each tr
. 但是我的代码只读取每个
tr
的第一个td
。
Here is my HTML : 这是我的HTML:
<table border="2px" id="tab">
<tr>
<td>color</td>
<td> a </td>
<td> font</td>
<td>123</td>
</tr>
<tr>
<td>font</td>
<td> color </td>
</tr>
<tr>
<td>a</td>
<td> color</td>
<td> font</td>
</tr>
<tr>
<td>font</td>
</tr>
</table>
My js code: 我的js代码:
var t=["color","font","a"];
function color()
{
var colr=0;
var tab=[];
var table = document.getElementById("tab");
var len=table.rows.length;
for (var i = 0; i< len; i++)
{
for (var j=0; j<table.rows[i].cells.length; j++)
{
tab[j]= table.rows[i].cells[j].innerHTML;
// alert(tab[j]);
if(tab[j]== t[0])
{ colr++;}
}
}
alert(colr);
}
What am I missing? 我想念什么?
The spacing in the <td>
is messing with the comparisons. <td>
的间距使比较混乱。 As your code lies, you're comparing " color"
to "color"
and that's returning false, thus seeing as you're only getting that colr
index going up to 1. 当您的代码位于时,您正在将
" color"
与"color"
进行比较,并且返回的是false,因此您看到的只是colr
索引升为1。
You'll need to strip out the spaces in order to compare properly, example JSFiddle here: https://jsfiddle.net/76q3aro3/ 您需要删除空格以进行正确比较,例如此处的JSFiddle: https ://jsfiddle.net/76q3aro3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.