简体   繁体   English

如何使用高效的 Javascript 在本地存储多个用户更改?

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

On my static webpage, users should be able to edit multiple texts and store changes locally to continue editing later.在我的 static 网页上,用户应该能够编辑多个文本并在本地存储更改以便以后继续编辑。 I put this together from code snippets by others (I myself am not a very competent user of Javascript).我从其他人的代码片段中将其组合在一起(我自己不是一个非常称职的 Javascript 用户)。

https://jsfiddle.net/x2thdrw3/54/ 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()">

The example is not efficient because the Javascript code would grow with each additional text.该示例效率不高,因为 Javascript 代码会随着每个附加文本而增长。

What would be a more efficient way to have multiple of these editable and storable divs on my webpage?在我的网页上拥有多个这些可编辑和可存储的 div 的更有效方法是什么?

On the webpage, the divs do not occur one after the other, like in the example, but with other noneditable content in between.在网页上,div 不会像示例中那样一个接一个地出现,而是在它们之间有其他不可编辑的内容。

PS: The code works on jsfiddle but stackoverflow throws a security error. PS:该代码适用于 jsfiddle,但 stackoverflow 会引发安全错误。 I do not understand why.我不懂为什么。 (Clarified by J. Titus in the comments.) (由 J. Titus 在评论中澄清。)

PPS: I am aware that I am asking a rather specific question. PPS:我知道我在问一个相当具体的问题。 Thank you for your help.谢谢您的帮助。

A very compact implementation.一个非常紧凑的实现。 ( Looks lengthy because of all the comments. ) 由于所有的评论看起来很长。

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 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()">

There are a few ways you could do this.有几种方法可以做到这一点。 One option is to have a specific attribute that your code can look for to apply the functionality.一种选择是拥有一个特定属性,您的代码可以查找该属性以应用该功能。

HTML with data-content-editable attribute: 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>

Then you can grab all elements that use data-content-editable and loop through them to apply the click event listener and the button.然后,您可以抓取所有使用 data-content-editable 的元素并循环遍历它们以应用单击事件侦听器和按钮。

JS 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.

相关问题 我如何在网页上存储由javascript所做的更改? - How do I have a web page store changes made by javascript? 用户使用Javascript输入后如何存储总积分? - How do I store total points after user input in Javascript? 如果用户使用 JavaScript 单击 cookie 上的按钮,我该如何存储? - How do I store if a user clicked a button on a cookie using JavaScript? 如何生成xml文件并允许用户使用javascript将其保存在本地? - how do I generate an xml file and allow the user to save it locally using javascript? 如何在一个 Javascript 对象中存储多个数据表? - How do I store multiple tables of data in one Javascript object? 如何在JavaScript变量中存储多个jQuery选择器? - How do I store multiple jQuery selectors in a javascript variable? 如何在 Jupyter 中本地引用 JavaScript 库? - How do I reference a JavaScript library locally in Jupyter? 如何在本地捆绑 JavaScript 和 CSS 依赖项以供离线使用? - How do I bundle JavaScript and CSS dependencies locally for offline use? 如何在 Linux Mint 本地服务我的 javascript 应用程序 - How do I serve my javascript app locally on Linux Mint Javascript不能在Heroku上工作但在本地工作,我该如何解决? - Javascript is not working on Heroku but works locally, how do I solve this?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM