首页 > 解决方案 > JS / jQuery - 如何一次获取两个 DIV 内容的文本?

问题描述

我想循环遍历我想在两个变量中写入相同元素的所有<TD>元素。我怎样才能在 JS / jQuery 中做到这一点?TitleLink<TD>

我的 HTML:

<td>
    <div class="class_Title row border-bottom" name="name_Title" id="id_Title">
        <B>Microsoft</B>
    </div>
    <div class="class_Link row" name="name_Link" id="id_Link">
        https://www.microsoft.com
    </div>
</td>

<td>
    <div class="class_Title row border-bottom" name="name_Title" id="id_Title">
        <B>Google</B>
    </div>
    <div class="class_Link row" name="name_Link" id="id_Link">
        https://www.google.com
    </div>
</td>
<!-- there are a lot of these...-->

我的Javascript:

    $('.class_Title').each(function(){
        var str_CurrentTitle = '';
        str_CurrentTitle= $(this).text().trim()

        $('.class_Link').each(function(){
            var str_CurrentLink = '';
            str_CurrentLink= $(this).text().trim()

            //call another function, to work with the result
            Start_To_Work_With_The_Result(str_CurrentTitle, str_CurrentLink)
        })
    })

预期的结果是,我可以使用参数(Microsoft / https://www.microsoft.com)调用函数 Start_To_Work_With_The_Result 一次,并在第二个循环中使用参数(Google / https://www.google.com)。

我怎样才能优雅地解决这个问题?

标签: javascriptjqueryhtml

解决方案


您的嵌套循环正在获取标题和链接的每个组合,而不仅仅是相关的对。

您应该只有一个循环,然后使用一种 DOM 导航方法来获取兄弟元素。

$(".class_Title").each(function() {
  var str_CurrentTitle = $(this).text().trim();
  var link = $(this).siblings(".class_Link");
  var str_CurrentLink = link.text().trim();
  Start_To_Work_With_The_Result(str_CurrentTitle, str_CurrentLink);
});

function Start_To_Work_With_The_Result(title, link) {
  console.log(title, link);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table><tr>
<td>
  <div class="class_Title row border-bottom" name="name_Title" id="id_Title">
    <B>Microsoft</B>
  </div>
  <div class="class_Link row" name="name_Link" id="id_Link">
    https://www.microsoft.com
  </div>
</td>

<td>
  <div class="class_Title row border-bottom" name="name_Title" id="id_Title">
    <B>Google</B>
  </div>
  <div class="class_Link row" name="name_Link" id="id_Link">
    https://www.google.com
  </div>
</td>
</tr></table>


推荐阅读