簡體   English   中英

重構方法鏈 javascript

[英]Refactor method chaining javascript

我用一堆嵌套方法調用 function,我正在使用 web 抓取工具,稱為cheerio,我想從中獲取文本,所以我需要調用一堆 ZC1C425268E687385D1AB5074C1 這是我的示例代碼。

        var text = $(el)
          .children()
          .first()
          .children()
          .first()
          .children()
          .first()
          .text()
          .replace(/\s\s+/g, " ");

我的問題是,我怎樣才能簡化我的 function 以便在不鏈接我的 function 的情況下得到相同的結果?

一個天真的解決方案可能是

var text = $(">*:nth-child(1)".repeat(3), el).text().replace(/\s+/g, " ");

對於一個好的解決方案,我們需要更多的上下文。 就像標記的樣子。

使用循環

let child = $(el).children().first()
if (child) {
 while (child.children().first()) {
   child = child.children().first()
 }
 child.text().replace(/\s\s+/g, " ");
}

您可以將nth-child(1)選擇器用於 select 第一個孩子。

你可以這樣使用

$("div div:nth-child(1) div:nth-child(1) ul:nth-child(1)").text()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM