jquery - 如何循环通过两个选定的元素?
问题描述
我想循环使用HTML
页面的两个类,jQuery
并且我正在尝试使用每个循环,但问题是我在哪里可以访问回调函数中的两个选定类?
var href = [];
$("div.news > ul > li:nth-child(1) > a , div.aticle ").each((el, i) => {
var baseURL = "someURL";
var link = baseURL + $(i).attr("href");
var text =
/* i want to access text() of div.article along with the href
of the div.news in this loop and then push it into href array */
href.push({
link
});
});
我想在这个循环中使用 jquery 的 text() 函数以及div.news访问 div.article的文本,然后将其推送到数组中。href
href
解决方案
考虑以下:
var href = [];
var text = [];
$("div.news > ul > li:nth-child(1) > a, div.article").each((el, i) => {
if ($(i).is(".article"))
text.push($(i).text());
else {
var baseURL = "someURL";
var link = baseURL + $(i).attr("href");
href.push(link);
}
});
console.log(href, text)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="news">
<ul>
<li>
<a href="www.google.com"></a>
</li>
</ul>
<ul>
<li>
<a href="www.bing.com"></a>
</li>
</ul>
<ul>
<li>
<a href="www.duckduckgo.com"></a>
</li>
</ul>
</div>
<div class="article">
text
</div>
推荐阅读
- javascript - Window.location 在 Javascript 中不起作用
- pandas - Pandas 从多列和滚动时间索引中获取最大值
- flutter - 如何使用颤振在共享首选项中保存布尔值?
- python - 根据字符串在新列中添加值包含在另一列中
- r - 使用 r 中 csv 中的文件名模式使用 for 循环重复相同的任务
- javascript - 如何在飞镖中连接和使用扩展运算符
- javascript - 根据当前的“日期”动态呈现以下工作日
- react-native - 错误:尝试更新 expo-cli 时“操作被您的操作系统拒绝”
- selenium-webdriver - 在自动上传文件时,katalon 和 eclipse 都面临这个问题。下面详细提到
- javascript - 如何在页面刷新时保持套接字实例?