Javascript 如何对th中的每个数字求和
我有一张有tr和th的桌子 我有——里面有数字值和IMG; 我需要找到所有th中的数值之和。 此脚本不等于“0”。虫子在哪里Javascript 如何对th中的每个数字求和,javascript,html,dom-manipulation,Javascript,Html,Dom Manipulation,我有一张有tr和th的桌子 我有——里面有数字值和IMG; 我需要找到所有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 +
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);
}
函数sumOfTh(){
设th=document.getElementsByTagName('th');
设res=0;
对于(i=0;i
这里是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>
1.
3.
5.
6.
7.
8.
9
10
11
12
13
14
15
16
17
18
19
将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;
}
函数sumOfTh(){
设th=document.getElementsByTagName('th');
设res=0;
对于(i=0;i
ths[i]。值未定义。您要查找的是文本内容
您还需要检查它是否为NaN且不为空
你需要回到循环之外。您将在第一次迭代后返回
工作示例
函数sumOfTh(){
设th=document.getElementsByTagName('th');
设res=0;
for(设i=0;i
您将在循环的第一轮退出函数。将return语句从循环体移到函数体的末尾。一个用于。。。循环< /代码>不需要<代码>返回< /代码>,除非您想退出循环中间的函数。这几乎是[i]的重复。值将是未定义的。请在开始前显示一些HTML。
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;
}