簡體   English   中英

如何使用高效的 Javascript 在本地存儲多個用戶更改?

[英]How do I store multiple user changes locally with efficient Javascript?

在我的 static 網頁上,用戶應該能夠編輯多個文本並在本地存儲更改以便以后繼續編輯。 我從其他人的代碼片段中將其組合在一起(我自己不是一個非常稱職的 Javascript 用戶)。

https://jsfiddle.net/x2thdrw3/54/

 window.onload = function() { if (localStorage.getItem('userContent01')) { document.querySelector('#userContent01').innerHTML = localStorage.getItem('userContent01'); } if (localStorage.getItem('userContent02')) { document.querySelector('#userContent02').innerHTML = localStorage.getItem('userContent02'); } } let editBtn01 = document.querySelector('#userContent01_edit'); let content01 = document.querySelector('#userContent01'); editBtn01.addEventListener('click', () => { localStorage.setItem('userContent01', content01.innerHTML); }); let editBtn02 = document.querySelector('#userContent02_edit'); let content02 = document.querySelector('#userContent02'); editBtn02.addEventListener('click', () => { localStorage.setItem('userContent02', content02.innerHTML); });
 .userContent { border: ridge 2px; padding: 15px; width: 100%; min-height: 2em; overflow: auto; }
 <div class="userContent", id="userContent01" contenteditable="true"> Edit this first text and then click save to store your changes for later. </div> <button id="userContent01_edit">Store changes to the first text locally</button> <div class="userContent", id="userContent02" contenteditable="true"> Edit this second text and then click save to store your changes for later. </div> <button id="userContent02_edit">Store changes to the second text locally</button> <br> <br> <input type="button" value="Reload and keep local storage" onClick="location.reload()"> <input type="button" value="Reload and clear local storage" onClick="localStorage.clear() + location.reload()">

該示例效率不高,因為 Javascript 代碼會隨着每個附加文本而增長。

在我的網頁上擁有多個這些可編輯和可存儲的 div 的更有效方法是什么?

在網頁上,div 不會像示例中那樣一個接一個地出現,而是在它們之間有其他不可編輯的內容。

PS:該代碼適用於 jsfiddle,但 stackoverflow 會引發安全錯誤。 我不懂為什么。 (由 J. Titus 在評論中澄清。)

PPS:我知道我在問一個相當具體的問題。 謝謝您的幫助。

一個非常緊湊的實現。 由於所有的評論看起來很長。

window.onload = function () {
  //Get all userContent elements
  let userContent_els = document.querySelectorAll(".user-content");
  
  //Loop over each userContent element
  userContent_els.forEach((el) => {
    // easy access using the id of the user content as key
    let key = el.id;
    let value = localStorage.getItem(key);

    if(value)
      el.innerText = value;
  });
};

//Get all button elements
let editButton_els = document.querySelectorAll(".edit-button");

//Loop over each button
editButton_els.forEach((button) => {
  let buttonId = button.id;

  button.addEventListener("click", () => {
    /* Storage key is a combination of 'content-' and the button 'id'.
       This combination is intentional as to make it easier getting the data later as we 
       just have to get the content 'id' which is set to 'content-01', 'content-02' etc..*/

    // Get corresponding userContent element
    let content_el = document.querySelector(`#content-${buttonId}`);

    localStorage.setItem(
     "content-" + buttonId,
     content_el.innerText
    );
  });
});

HTML

<div class="user-content" , id="content-01" contenteditable="true">
  Edit this first text and then click save to store your changes for later.
</div>

<button class="edit-button" id="01">Store changes to the first text locally</button>

<div class="user-content" , id="content-02" contenteditable="true">
  Edit this second text and then click save to store your changes for later.
</div>

<button class="edit-button" id="02">Store changes to the second text locally</button>

<br>
<br>

<input type="button" value="Reload and keep local storage" onClick="location.reload()">

<input type="button" value="Reload and clear local storage" onClick="localStorage.clear() + location.reload()">

有幾種方法可以做到這一點。 一種選擇是擁有一個特定屬性,您的代碼可以查找該屬性以應用該功能。

HTML 具有數據內容可編輯屬性:

<div class="userContent" id="userContent01" data-content-editable="true">
  Edit this first text and then click save to store your changes for later.
</div>

<div class="userContent" id="userContent02" data-content-editable="true">
  Edit this second text and then click save to store your changes for later.
</div>

然后,您可以抓取所有使用 data-content-editable 的元素並循環遍歷它們以應用單擊事件偵聽器和按鈕。

JS

  document
    .querySelectorAll('[data-content-editable="true"]')
    .forEach((element) => {
      const elementId = element.getAttribute("id");

      if (localStorage.getItem(elementId)) {
        element.innerHTML = localStorage.getItem(elementId);
      }

      const btn = document.createElement("button");
      btn.innerHTML = `Store changes to ${elementId} locally`;
      btn.type = "button";

      btn.addEventListener("click", () => {
        localStorage.setItem(elementId, element.innerHTML);
      });

      element.appendChild(btn);
    });

暫無
暫無

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

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