作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想遍历所有 <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/
我是一名优秀的程序员,十分优秀!