有没有什么方法可以在不使用 this
的情况下重写这个 Cheerio 嵌套循环?
$("tr").each(function(i) {
$(this)
.find(".windowbg>[id^=msg]")
.each(function(i) {
const link = $(this).find("a");
const subject: string = link.text();
const id = extractId(link.prop("href"));
threads.push(new Thread(id, subject));
});
});
最佳答案
jQuery
如果您使用命名参数,则不需要使用this
。在 jQuery 中,.each()
的第二个参数是上下文中的元素(相当于 this),所以你会 $('tr').each(function(index, element){ ... })
$("tr").each(function(i, tr) {
$(tr)
.find(".windowbg>[id^=msg]")
.each(function(i, msg) {
const link = $(msg).find("a");
const subject: string = link.text();
const id = extractId(link.prop("href"));
threads.push(new Thread(id, subject));
});
});
ES6+
你可以完全避免使用 ES6 和更高版本的 jQuery。箭头函数(和 forEach
)有助于缩短语法:
let rows = document.querySelectorAll('tr')
rows.forEach(row => {
let messages = row.querySelectorAll('.windowbg > [id^=msg]')
messages.forEach(message => {
const link = message.querySelector('a')
const subject = link.textContent
const id = link.href // extractId(link.href)
console.log(`id: ${id}`)
// threads.push(new Thread(id,subject)
})
})
table,
td {
border: 1px solid #999;
border-collapse: collapse
}
td {
padding: .75rem
}
table {
width: 75%;
margin: 0 auto;
}
<table>
<tbody>
<tr>
<td class="windowbg">
<span id="msg1"><a href="#link1">Link</a></span>
<span id="notmsg1"><a href="#foo2">Foo</a></span>
<div>Other Text</div>
</td>
<td>Other Cell</td>
</tr>
<tr>
<td class="windowbg">
<span id="msg2"><a href="#link2">Link</a></span>
<span id="notmsg2"><a href="#foo2">Foo</a></span>
<div>Other Text 2</div>
</td>
<td>Other Cell</td>
</tr>
</tbody>
</table>
关于javascript - 在不使用 "this"的情况下引用 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613731/