vanilla JS:将不同的函数存储为localStorage中的一个键的不同值

问题描述 投票:0回答:1

这是一个代码和一个问题本身:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .size {
        width: 100px;
        height: 100px;
      }

      .hiddenimage {
        display: none;
      }

      .activeimage {
        background-color: orange;
      }

      .text1color {
        color: green;
      }

      .text2color {
        color: red;
      }

      .text3color {
        color: blue;
      }

      .text4color {
        color: purple;
      }

      .text5color {
        color: brown;
      }
    </style>
  </head>
  <body>
    <div>
      <img
        class="image1isvisible size"
        onclick="switchToImage2()"
        src="https://upload.wikimedia.org/wikipedia/commons/a/a8/Eo_circle_green_white_number-1.svg"
      />
      <img
        class="image2isvisible size"
        onclick="switchToImage3()"
        src="https://upload.wikimedia.org/wikipedia/commons/8/85/Eo_circle_red_white_number-2.svg"
      />
      <img
        class="image3isvisible size"
        onclick="switchToImage4()"
        src="https://upload.wikimedia.org/wikipedia/commons/1/1a/Eo_circle_blue_white_number-3.svg"
      />
      <img
        class="image4isvisible size"
        onclick="switchToImage5()"
        src="https://upload.wikimedia.org/wikipedia/commons/7/79/Eo_circle_purple_white_number-4.svg"
      />
      <img
        class="image5isvisible size"
        onclick="switchToImage1()"
        src="https://upload.wikimedia.org/wikipedia/commons/2/28/Eo_circle_brown_white_number-5.svg"
      />
    </div>
    <p class="text">
      If the localStorage is clear (on the first load), the state is like now:
      all five images are shown, all five images are not active (orange
      rectangular is not visible) and the colour of this text is default
      (black).<br />When user clicks on one of the images, four other images
      become hidden and only one image with the following number is shown. This
      text obtains colour of the visible image circle. The same happens on the
      folllowing clicks. So, images change sequentially (1, 2, 3, 4, 5, 1, 2, 3,
      4, 5, 1, 2, 3, ...) when user clicks on them and this text obtains the
      same colour as the circle on the image.<br />The last shown (=active,
      =current) image and the colour of the text should be stored in the
      localStorage.<br />
      On the page reload current active image and current text colour should be
      retrieved from the localStorage and shown.<br />Please, use
      <strong>only vanilla JS</strong>, no jQuery, no other libraries or
      frameworks. It is also important to preserve 5 independant functions
      (switchToImage2, ... switchToImage5, switchToImage1) for changing these 5
      images. Additions to these functions, new necessary functions or necessary
      editions (new classes, indeces, identificators, whatever) to the code in
      general are welcomed.<br />So, everyhing what was described above (instead
      of localStorage) is working as it should work and
      <strong>the only task is to store state in the localStorage</strong
      >.<br />Probably it will be necessary to store the whole function in the
      localStorage. For this purpose
      <a
        href="https://stackoverflow.com/a/38926742/17339653"
        target="_blank"
        rel="noopener noreferrer"
        >this</a
      >
      solution may be helpful.<br />If it is possible, it would be great to
      preserve the state with only one key in the localStorage. If it is
      impossible - you are welcomed to create different keys for visible image,
      its active orange rectangular and text colour.<br />I hope you will find
      this challenge interesting!<br />Could you copypaste my code, edit it and
      answer with a snippet that will possess all the abovementioned
      localStorage functionality?<br />Thank you a lot!
    </p>
    <script>
      const isText = document.querySelector(".text");
      const isimage1 = document.querySelector(".image1isvisible");
      const isimage2 = document.querySelector(".image2isvisible");
      const isimage3 = document.querySelector(".image3isvisible");
      const isimage4 = document.querySelector(".image4isvisible");
      const isimage5 = document.querySelector(".image5isvisible");

      function switchToImage2() {
        // removeotherstyle
        isimage1.classList.remove("activeimage");
        isimage3.classList.remove("activeimage");
        isimage4.classList.remove("activeimage");
        isimage5.classList.remove("activeimage");
        isimage1.classList.add("hiddenimage");
        isimage3.classList.add("hiddenimage");
        isimage4.classList.add("hiddenimage");
        isimage5.classList.add("hiddenimage");
        isText.classList.remove("text1color");
        isText.classList.remove("text3color");
        isText.classList.remove("text4color");
        isText.classList.remove("text5color");
        // add2style
        isimage2.classList.remove("hiddenimage");
        isimage2.classList.add("activeimage");
        isText.classList.add("text2color");
      }

      function switchToImage3() {
        // removeotherstyle
        isimage1.classList.remove("activeimage");
        isimage2.classList.remove("activeimage");
        isimage4.classList.remove("activeimage");
        isimage5.classList.remove("activeimage");
        isimage1.classList.add("hiddenimage");
        isimage2.classList.add("hiddenimage");
        isimage4.classList.add("hiddenimage");
        isimage5.classList.add("hiddenimage");
        isText.classList.remove("text1color");
        isText.classList.remove("text2color");
        isText.classList.remove("text4color");
        isText.classList.remove("text5color");
        // add3style
        isimage3.classList.remove("hiddenimage");
        isimage3.classList.add("activeimage");
        isText.classList.add("text3color");
      }

      function switchToImage4() {
        // removeotherstyle
        isimage1.classList.remove("activeimage");
        isimage2.classList.remove("activeimage");
        isimage3.classList.remove("activeimage");
        isimage5.classList.remove("activeimage");
        isimage1.classList.add("hiddenimage");
        isimage2.classList.add("hiddenimage");
        isimage3.classList.add("hiddenimage");
        isimage5.classList.add("hiddenimage");
        isText.classList.remove("text1color");
        isText.classList.remove("text2color");
        isText.classList.remove("text3color");
        isText.classList.remove("text5color");
        // add4style
        isimage4.classList.remove("hiddenimage");
        isimage4.classList.add("activeimage");
        isText.classList.add("text4color");
      }

      function switchToImage5() {
        // removeotherstyle
        isimage1.classList.remove("activeimage");
        isimage2.classList.remove("activeimage");
        isimage3.classList.remove("activeimage");
        isimage4.classList.remove("activeimage");
        isimage1.classList.add("hiddenimage");
        isimage2.classList.add("hiddenimage");
        isimage3.classList.add("hiddenimage");
        isimage4.classList.add("hiddenimage");
        isText.classList.remove("text1color");
        isText.classList.remove("text2color");
        isText.classList.remove("text3color");
        isText.classList.remove("text4color");
        // add5style
        isimage5.classList.remove("hiddenimage");
        isimage5.classList.add("activeimage");
        isText.classList.add("text5color");
      }

      function switchToImage1() {
        // removeotherstyle
        isimage2.classList.remove("activeimage");
        isimage3.classList.remove("activeimage");
        isimage4.classList.remove("activeimage");
        isimage5.classList.remove("activeimage");
        isimage2.classList.add("hiddenimage");
        isimage3.classList.add("hiddenimage");
        isimage4.classList.add("hiddenimage");
        isimage5.classList.add("hiddenimage");
        isText.classList.remove("text2color");
        isText.classList.remove("text3color");
        isText.classList.remove("text4color");
        isText.classList.remove("text5color");
        // add1style
        isimage1.classList.remove("hiddenimage");
        isimage1.classList.add("activeimage");
        isText.classList.add("text1color");
      }
    </script>
  </body>
</html>

如果 localStorage 是清晰的(在第一次加载时),状态就像现在: 显示所有五个图像,所有五个图像均未激活(橙色 矩形不可见)并且此文本的颜色为默认颜色 (黑色)。

当用户点击其中一张图片时,其他四张图片 变得隐藏,只显示具有以下编号的一张图像。这 text 获取可见图像圆圈的颜色。同样的事情发生在 以下点击。因此,图像顺序变化 (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, ...) 当用户点击它们并且此文本获得 与图像上的圆圈颜色相同。

最后显示的(=活动的, =current) 图像和文本的颜色应该存储在 本地存储。

在页面上重新加载当前活动图像和当前 文本颜色应该从 localStorage 中检索并显示。

拜托,只使用 vanilla JS,没有 jQuery,没有其他库或 构架。保留 5 个独立的功能也很重要 (switchToImage2, ... switchToImage5, switchToImage1) 用于更改这 5 图片。添加这些功能,新的必要功能或必要的 欢迎使用一般代码的版本(新类、索引、标识符等)。

所以,一切都是 上面描述的(而不是 localStorage)正在正常工作,并且 唯一的任务是将状态存储在 localStorage.

可能需要将整个函数存储在 本地存储。以此目的 this 解决方案可能会有帮助。

如果可以的话,那就太好了 在 localStorage 中只用一个键保存状态。如果是 不可能 - 欢迎您为可见图像创建不同的密钥, 它的活动橙色矩形和文本颜色。

我希望你会发现这个挑战很有趣!

你能复制粘贴我的代码,编辑它并用一个将拥有上述所有 localStorage 功能的片段回答吗?

非常感谢!

UPD 2023.04.10:经过数小时的多次尝试,这个问题仍然相关...... 还有一个 JSFiddle 可用: https://jsfiddle.net/maksymkushnirov/5rkh46ec/1/

javascript local-storage tostring
1个回答
0
投票

这里有一种简单的方法可以实现您的愿望。我试图避免更高级的构造,例如数组方法,因为您才刚刚开始编程,我不希望您被它搞糊涂。我还剪切了文本,因为您可以根据需要替换占位符并缩短此示例。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .size {
        width: 100px;
        height: 100px;
      }

      .hiddenimage {
        display: none;
      }

      .activeimage {
        background-color: orange;
      }

      .text1color {
        color: green;
      }

      .text2color {
        color: red;
      }

      .text3color {
        color: blue;
      }

      .text4color {
        color: purple;
      }

      .text5color {
        color: brown;
      }
    </style>
  </head>
  <body>
    <div>
      <img
        class="size"
        src="https://upload.wikimedia.org/wikipedia/commons/a/a8/Eo_circle_green_white_number-1.svg"
      />
      <img
        class="size"
        src="https://upload.wikimedia.org/wikipedia/commons/8/85/Eo_circle_red_white_number-2.svg"
      />
      <img
        class="size"
        src="https://upload.wikimedia.org/wikipedia/commons/1/1a/Eo_circle_blue_white_number-3.svg"
      />
      <img
        class="size"
        src="https://upload.wikimedia.org/wikipedia/commons/7/79/Eo_circle_purple_white_number-4.svg"
      />
      <img
        class="size"
        src="https://upload.wikimedia.org/wikipedia/commons/2/28/Eo_circle_brown_white_number-5.svg"
      />
    </div>
    <p class="text">
      Text goes here
    </p>
    <script>
      const sizesElements = document.querySelectorAll(".size");
      const textElement = document.querySelector(".text");
      
      function resetClasses() {
        for (let i = 0; i < sizesElements.length; i++) {
          const element = sizesElements[i];
          element.classList.remove("activeimage");
          element.classList.add("hiddenimage");
          textElement.classList.remove(`text${i + 1}color`);
        }
      }
      
      function showSizeSelector(index) {
        const element = sizesElements[index];
        element.classList.add("activeimage");
        element.classList.remove("hiddenimage");
      }
      
      function styleParagraph(index) {
        textElement.classList.add(`text${index + 1}color`);
      }
      
      function addEventListenerToSizeSelector(element, index) {
        element.addEventListener('click', function() {
          resetClasses(); // will make all 5 size selectors disappear
          showSizeSelector(index); // will make the correct size selector appear
          styleParagraph(index); // adds the correct class to the paragraph
          localStorage.setItem("LSImage", index); // saves the selection to local storage
        })
      }
      
      // Attach "onclick" to each of the size selectors
      for (let i = 0; i < sizesElements.length; i++) {
        addEventListenerToSizeSelector(sizesElements[i], i);
      }
      
      
      const currentImage = localStorage.getItem("LSImage");
      // if on load something is stored in local storage, handle it
      if (currentImage) {
        const currentImageIndex = Number(currentImage); // local storage always stores data as strings
        resetClasses();
        showSizeSelector(currentImageIndex);
        styleParagraph(currentImageIndex);
      }
    </script>
  </body>
</html>

请注意,我去掉了每个

onclick
标签上的
img
,而是使用函数
addEventListener
将事件处理程序附加到 DOM 元素。您可以在here查看此功能的更多详细信息。不要将它与
addEventListenerToSizeSelector
混淆,这是我声明的功能,只是为了让事情更有条理。

有了它,我可以为每个尺寸选择器使用相同的函数,因为我传递给它的参数是不同的。最后,我添加了一个只运行一次的检查(当脚本加载时),检查是否有任何信息存储在“LSImage”键下。如果有,请注意我使用了相同的功能,但传递了我检索到的信息以正确地将界面设置为正确的颜色。

我不知道我是否不清楚某些信息,但随时要求任何澄清和愉快的编码:)

© www.soinside.com 2019 - 2024. All rights reserved.