我有一张桌子,上面有tr和th我有-带有数字值和内部的imgs;我需要在所有th中找到数字值的总和。该脚本的确等于“ 0”。错误在哪里??
function sumOfTh(){
let ths = document.getElementsByTagName('th');
let res = 0;
for (i = 0; i < ths.length; i++) {
if (isNaN(ths[i].value)) {
res += 0;
} else {
res += parseInt(ths[i].value);
}
return res;
}
console.log(res);
}
这里是HTML
<table class="border" id="myTable">
<tr>
<th colspan="2">1</th>
<th><a href="https://www.w3schools.com/css/css_quiz.asp" ><img class="img" src="cell.jpg"></a></th>
<th>3</th>
<th><a href="https://www.testdome.com/tests/html-css-online-test/13"><img class="img" src="cell.jpg"></a></th>
</tr>
<tr>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
</tr>
<tr>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
</tr>
<tr>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
</tr>
</table>
向下移动return语句,然后它应该起作用
function sumOfTh(){
let ths = document.getElementsByTagName('th');
let res = 0;
for (i = 0; i < ths.length; i++) {
if (isNaN(ths[i].value)) {
res += 0;
} else {
res += parseInt(ths[i].value);
}
}
console.log(res);
return res;
}
ths[i].value
未定义。您要查找的是textContent。
还需要检查它是否不是NaN 和不为空。
并且您需要返回循环之外。您将在第一次迭代后返回。
工作示例https://jsfiddle.net/g3he2ts8/3/
function sumOfTh(){
let ths = document.getElementsByTagName('th');
let res = 0;
for (let i = 0; i < ths.length; i++) {
let content = ths[i].textContent;
if (!isNaN(content) && content !== '') {
res += parseInt(content);
}
}
console.log(res);
return res;
}