引用“ this”而不使用“ this”

时间:2018-10-02 17:50:36

标签: javascript cheerio

是否有任何方法可以在不使用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));
      });
  });

2 个答案:

答案 0 :(得分:3)

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>

答案 1 :(得分:0)

您可以使用箭头功能(ES6 +)来做到这一点

$("tr").each((i, tr) => {
  $(tr).find(...) // access the element
  this.xxx // "this" is original scope
})