gpt4 book ai didi

javascript - JS/jQuery - 如何一次获取两个 DIV 内容的文本?

转载 作者:行者123 更新时间:2023-11-30 09:17:41 26 4
gpt4 key购买 nike

我想遍历所有 <TD>我要写 Title 的元素和 Link相同的 <TD>两个变量中的元素。我如何在 JS/jQuery 中做到这一点?

我的 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)。

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

最佳答案

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

您应该只有一个循环,然后使用 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>

关于javascript - JS/jQuery - 如何一次获取两个 DIV 内容的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952699/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com