Избегайте for-l oop с помощью QuerySelector внутри таблицы - PullRequest
1 голос
/ 04 августа 2020

Я пытаюсь получить список нескольких записей для каждой строки из таблицы с помощью querySelectorAll , но я пытался одним способом, но застрял внутри нескольких for-l oop.

Я хочу знать, есть ли более подходящий способ решения этой конкретной c проблемы с функцией querySelectorAll?

То, что я пробовал до сих пор:

Html извлечено так далеко от: var innerT = t2[i].cells;

t2 = document.querySelectorAll('.flexible.block_xp-report-table tbody tr');
for (var i = 0; i < t2.length; i++) {
  var innerT = t2[i].cells; //the generated HTML is from this steps
  for (var j = 0; j < innerT.length; j++) {
    var innerT1 = innerT[j].cells;
    for (var k = 0; k < innerT1.length; k++) {
      console.log(innerT1[k])
    }
  }
}
<table cellspacing="0" class="flexible block_xp-report-table" id="yui_3_17_2_1_1596535723450_172">
  <thead id="yui_3_17_2_1_1596535723450_189">
    <tr id="yui_3_17_2_1_1596535723450_188">
      <th class="header c0" scope="col" id="yui_3_17_2_1_1596535723450_187">
        S.N
      </th>
      <th class="header c1" scope="col" id="yui_3_17_2_1_1596535723450_198">
        Name
      </th>
      <th class="header c2" scope="col">
        Level
      </th>
      <th class="header c3" scope="col">
        Point
      </th>
    </tr>
  </thead>
  <tbody id="yui_3_17_2_1_1596535723450_171">
    <tr class="" id="block_xp_report_r0">
      <td class="cell c0" id="block_xp_report_r0_c0">
        <a href="http://test.com.np/user/view.php?id=2157&amp;course=103">Image 1</a>
      </td>
      <td class="cell c1" id="block_xp_report_r0_c1">
        <a href="http://test.com.np/user/view.php?id=2157&amp;course=103" id="yui_3_17_2_1_1596532113936_188">John</a>
      </td>
      <td class="cell c2" id="block_xp_report_r0_c2">6</td>
      <td class="cell c3" id="block_xp_report_r0_c3">
        <div class="block_xp-xp">
          <div class="pts">6,414</div>
          <div class="sign sign-sup">xp</div>
        </div>
      </td>
    </tr>
    <tr class="" id="block_xp_report_r1">
      <td class="cell c0" id="block_xp_report_r1_c0">
        <a href="http://test.com.np/user/view.php?id=2158&amp;course=103">Image 1</a>
      </td>
      <td class="cell c1" id="block_xp_report_r1_c1">
        <a href="http://test.com.np/user/view.php?id=2158&amp;course=103" id="yui_3_17_2_1_1596532113936_188">John</a> -- -- I the value of href only

      </td>
      <td class="cell c2" id="block_xp_report_r1_c2">6</td> -- I need this number only
      <td class="cell c3" id="block_xp_report_r1_c3">
        <div class="block_xp-xp">
          <div class="pts">6,414</div> -- I need this number only
          <div class="sign sign-sup">xp</div>
        </div>
      </td>
    </tr> --- this tr will go expanding ---
  </tbody>
</table>

Ответы [ 2 ]

1 голос
/ 04 августа 2020

<body onload="init()">
    <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

    <table class="block_xp-report-table">
        <tbody>
            <tr class="" id="block_xp_report_r0">
                <td class="cell c0" id="block_xp_report_r0_c0">
                    1
                </td>
                <td class="cell c1" id="block_xp_report_r0_c1">
                    <a href="http://test.com.np/user/view.php?id=2157&amp;course=103"
                        id="yui_3_17_2_1_1596532113936_188"
                        data-attribute="-- need to get the href value from here not the name">John</a>
                </td>
                <td class="cell c2" id="block_xp_report_r0_c2" data-attribute="---need to get this text ">6</td>
                <td class="cell c3" id="block_xp_report_r0_c3">
                    <div class="block_xp-xp">
                        <div class="pts" data-attribute="---need to get this text ">6,414</div>
                    </div>
                </td>
            </tr>
            <tr class="" id="block_xp_report_r1">
                <td class="cell c0" id="block_xp_report_r1_c0">
                    <a href="http://test.com.np/user/view.php?id=2158&amp;course=103">Image 1</a>
                </td>
                <td class="cell c1" id="block_xp_report_r1_c1">
                    <a href="http://test.com.np/user/view.php?id=2158&amp;course=103"
                        id="yui_3_17_2_1_1596532113936_188">John</a>
                </td>
                <td class="cell c2" id="block_xp_report_r1_c2">6</td>
                <td class="cell c3" id="block_xp_report_r1_c3">
                    <div class="block_xp-xp">
                        <div class="pts">6,414</div>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>


    <script>

        function init() {

            const rowIndexes = {

                href: 1,
                text: 2,
                points: 3
            }

            const responses = Array.from(document.querySelectorAll('.block_xp-report-table tbody tr'))
                .map(res => {



                    const getFor = (elemName) => {
                        return res.querySelectorAll("td")[rowIndexes[elemName]]
                    }


                    return { href: getFor('href').querySelector("a").getAttribute("href"), text: getFor('text').innerText, points: getFor('points').innerText }
                })

            console.log(responses)

          
        }

    </script>
</body>

Результат будет (при условии, что класс таблицы - block_xp-report-table)

[{"href":"http://test.com.np/user/view.php?id=2157&course=103","text":"6","points":"6,414"},{"href":"http://test.com.np/user/view.php?id=2158&course=103","text":"6","points":"6,414"}]

1 голос
/ 04 августа 2020

Вы также можете использовать querySelector (аналогично querySelectorAll, но возвращать только первый совпадающий элемент) в html object. Таким образом, t2[i].querySelector('.c1 a') вернет a внутри td, который имеет класс c1 внутри t2[i]. Затем получите значение href, используя .getAttribute('href');.

Аналогично используйте t2[i].querySelector('.pts').innerText;, чтобы получить div с классом pts внутри t2[i]. Введите innerText, чтобы получить text из div.

Попробуйте ниже.

var t2 = document.querySelectorAll('.flexible.block_xp-report-table tbody tr');
for (var i = 0; i < t2.length; i++) {
  var href = t2[i].querySelector('.c1 a').getAttribute('href');
  console.log(href);
  var pts = t2[i].querySelector('.pts').innerText;
  console.log(pts);
}
<table cellspacing="0" class="flexible block_xp-report-table" id="yui_3_17_2_1_1596535723450_172">
  <thead id="yui_3_17_2_1_1596535723450_189">
    <tr id="yui_3_17_2_1_1596535723450_188">
      <th class="header c0" scope="col" id="yui_3_17_2_1_1596535723450_187">
        S.N
      </th>
      <th class="header c1" scope="col" id="yui_3_17_2_1_1596535723450_198">
        Name
      </th>
      <th class="header c2" scope="col">
        Level
      </th>
      <th class="header c3" scope="col">
        Point
      </th>
    </tr>
  </thead>
  <tbody id="yui_3_17_2_1_1596535723450_171">
    <tr class="" id="block_xp_report_r0">
      <td class="cell c0" id="block_xp_report_r0_c0">
        <a href="http://test.com.np/user/view.php?id=2157&amp;course=103">Image 1</a>
      </td>
      <td class="cell c1" id="block_xp_report_r0_c1">
        <a href="http://test.com.np/user/view.php?id=2157&amp;course=103" id="yui_3_17_2_1_1596532113936_188">John</a>
      </td>
      <td class="cell c2" id="block_xp_report_r0_c2">6</td>
      <td class="cell c3" id="block_xp_report_r0_c3">
        <div class="block_xp-xp">
          <div class="pts">6,414</div>
        </div>
      </td>
    </tr>
    <tr class="" id="block_xp_report_r1">
      <td class="cell c0" id="block_xp_report_r1_c0">
        <a href="http://test.com.np/user/view.php?id=2158&amp;course=103">Image 1</a>
      </td>
      <td class="cell c1" id="block_xp_report_r1_c1">
        <a href="http://test.com.np/user/view.php?id=2158&amp;course=103" id="yui_3_17_2_1_1596532113936_188">John</a>
      </td>
      <td class="cell c2" id="block_xp_report_r1_c2">6</td>
      <td class="cell c3" id="block_xp_report_r1_c3">
        <div class="block_xp-xp">
          <div class="pts">6,414</div>
        </div>
      </td>
    </tr>
  </tbody>
</table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...