簡體   English   中英

如何將.each()的結果存儲到localStorage中?

[英]How can I store the result of .each() into localStorage?

這是我的代碼:

localStorage.setItem('qandaInputsValue7', $("#ask_q_tags span:first-child, #ask_q_tags span + span").each(function() { return $( this )[0].outerHTML }));

結果是:

在此處輸入圖片說明

如您所見,這是一個沒有用的對象。


預期的結果是:( 應作為localStorage中該鍵的值)

<span>something</span><span>something else</span>

看到? 我需要制作一個return $( this )[0].outerHTML的組合字符串,以將其設置為localStorage。 我怎樣才能做到這一點?


請注意, JSON.stringify().get()都不起作用。

.each()僅執行迭代邏輯,不返回任何內容。 您正在尋找的是使用.map()並將其與.get()以檢索實際輸出。 最后,您需要將返回的數組轉換為JSON,以便可以將其存儲為純文本:

var htmlToStore = JSON.stringify(
    $("#ask_q_tags span:first-child, #ask_q_tags span + span")
        .map(function() {
            return this.outerHTML;
        })
        .get()
);

localStorage.setItem('qandaInputsValue7', htmlToStore);

請注意,您不必使用$(this)[0].outerHTML來引用原始DOM節點,而是可以使用this.outerHTML :) htmlToStore將是一個數組,因此,如果要使用真正的字符串,則必須使用.join('')折疊數組。

使用map代替each ,然后getjoin

localStorage.setItem('qandaInputsValue7', JSON.stringify( 
       $( "#ask_q_tags span:first-child, #ask_q_tags span + span" ).map( function() { 
           return $( this )[0].outerHTML 
       }).get().join(""); //get and join here
));

無需使用JSON.stringify

localStorage.setItem('qandaInputsValue7', 
       $( "#ask_q_tags span:first-child, #ask_q_tags span + span" ).map( function() { 
           return $( this )[0].outerHTML 
       }).get().join(""); //get and join here
);

暫無
暫無

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

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