javascript - JS / jQuery - 如何一次获取两个 DIV 内容的文本?
问题描述
我想循环遍历我想在两个变量中写入相同元素的所有<TD>
元素。我怎样才能在 JS / jQuery 中做到这一点?Title
Link
<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)。
我怎样才能优雅地解决这个问题?
解决方案
您的嵌套循环正在获取标题和链接的每个组合,而不仅仅是相关的对。
您应该只有一个循环,然后使用一种 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>
推荐阅读
- python - 将使用本地文件的 python 程序转换为 .exe
- docker - docker:绑定挂载主机文件夹:如何管理不同主机 uid:gid 的 dockerfiles
- oauth-2.0 - Google OAuth 的 login_hint 参数在 Safari 用户代理中不起作用
- kubernetes - 从外部访问 istio-service-mesh
- html - CSS初学者问题:按钮之间的额外可点击空间
- apache-camel - Apache Camel - 触发多播步骤后未使用执行线程
- python - 使用命令“gunicorn app:app”启动进程退出状态为 126
- django - 如何显示外键字段的名称而不是其 ID?
- javascript - 样式背景不显示图像
- google-sheets - 记录特定时间间隔的单元格值