как сложить каждое число внутри - PullRequest
1 голос
/ 24 апреля 2020

У меня есть таблица с tr и th, которые у меня есть - со значениями чисел и с imgs внутри; Мне нужно найти сумму числовых значений внутри всего го. Этот скрипт равен «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>

Ответы [ 2 ]

1 голос
/ 24 апреля 2020

ths[i].value не определено. То, что вы ищете, это textContent .

Также вам нужно убедиться, что это не NaN и не пусто.

И вам нужно вернуться за пределы l oop. Вы возвращаетесь после первой итерации.

Рабочий пример 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;
}
0 голосов
/ 24 апреля 2020

Переместите оператор возврата вниз, тогда он должен работать

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;
}
...