首页 > 解决方案 > 使用本地存储记住上次单击的按钮

问题描述

我正在尝试使用本地存储来保留最后点击的按钮,即使页面重新加载也是如此。我尝试了以下代码,但没有成功:http: //jsfiddle.net/2L0d64hv/1/

    $(document).ready(function() {
      $("#button").on("click", function() {
        $("#collapse").slideToggle("slow");
        if ($(this).val() == "Hide") {
          $(this).val("Show");
          $(this).attr("src","https://www.gravatar.com/avatar/2e83e2d35f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
        } else {
          $(this).val("Hide");
          $(this).attr("src","https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1");
        }
  localStorage.imageStatus = $('#button').data('status');
  
  });
  
  const initialStatus = localStorage.imageStatus || 'Hide';
$('#button').data('status', initialStatus);
  
});
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="image" value="Hide" id="button" src="https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1"></button>
<div id="collapse">
  Hello
</div>

标签: javascriptjquery

解决方案


不要使用变量。您已经localStorage.imageStatus
准备好阅读 DOM 并通过一些方便的可重用功能切换它:http: //jsfiddle.net/ch2mzftu/1/

const $btn = $("#button");
const $col = $("#collapse");

if (!localStorage.imageState) localStorage.imageState = "hide";

const toggleState = () => {
  localStorage.imageState = localStorage.imageState === "hide" ? "show" : "hide";
};

const applyState = () => {
  const isHide = localStorage.imageState === "hide";
  $col[isHide ? "slideUp" : "slideDown"]();
  $btn.attr("src",
    isHide ?
    "https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1" :
    "https://www.gravatar.com/avatar/2e83e2d35f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1"
  );
};

applyState();      // Apply state on DOM ready!

$btn.on("click", () => { 
  toggleState();   // Toggle LS value
  applyState();    // and apply new state!
});
<input type="image" data-status="Hide" id="button" src="https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=32&d=identicon&r=PG&f=1">
<div id="collapse">Hello</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

根据 localStorage 变量更改网站状态

另一个更好的解决方案是根本不使用 jQuery
而是通过 CSS 专门处理与元素中的data-hide属性相关的所需元素状态<html>

  • 使用渲染阻塞<script>(in <head>) 将暂停 DOM 解析器并将初始数据设置为html元素
  • 使用 JS切换data-hideHTML 元素的属性
  • 阅读更多:这里
<!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>TEST</title>

        <script>
            // Render blocking on purpose! Keep this here in <head>
            if (!localStorage.imageState) localStorage.imageState = "show";
            document.documentElement.dataset.state = localStorage.imageState;
        </script>

        <style>
            #button {
                border: 0;
                background: transparent;
            }
            #button img {
                display: none;
                height: 60px;
            }
            #collapse {
                transition: 0.5s;
                transform: translateY(-100%);
                opacity: 0;
            }
            html[data-state="hide"] #button img:nth-child(1) {
                display: inline-block;
            }
            html[data-state="show"] #button img:nth-child(2) {
                display: inline-block;
            }
            html[data-state="show"] #collapse {
                transform: translateY(0%);
                opacity: 1;
            }
        </style>
    </head>
    <body>

        <button id="button">
            <img src="https://www.gravatar.com/avatar/2e83e2d00f0b889da7d5905c7bf574c2?s=328&d=identicon&r=PG&f=1">
            <img src="https://i.stack.imgur.com/qCWYU.jpg?s=328&g=1">
        </button>
        <div id="collapse">Hello from Roko</div>

        <script>
            const EL_button = document.querySelector("#button");
            EL_button.addEventListener("click", () => {
                localStorage.imageState = localStorage.imageState === "show" ? "hide" : "show";
                document.documentElement.dataset.state = localStorage.imageState;
            });
        </script>
    </body>
</html>


推荐阅读