【问题标题】:save to localstorage with html jQuery使用 html jQuery 保存到本地存储
【发布时间】:2018-07-24 00:06:21
【问题描述】:

您好,我有一个大问题,我试图解决,但它不起作用。当您单击卡片 (.card-1) 时,我希望卡片为 fadeOut,并将其保存在 localStorage

该功能有效但未保存在localStorage中,我做错了什么,我尝试了很多不同的东西?

似乎getItem 有效,因为该功能运行,但是当我刷新应用程序时,卡片仍然存在。我使用的是 card-1 类而不是输入的部分

<section class="card-1"></section>

感谢您的帮助

$(".card-1").click(function() {
  var storage = $(".card-1").val;
  if (localStorage.getItem("local", storage)) {
    $('.card-1').fadeOut();

    localStorage.setItem("local", storage);
  }
});

【问题讨论】:

  • 开发者工具有一个标签(Storage 用于 FF,Application -> Storage 用于 Chrome)显示本地存储中的内容。您能否验证您的数据实际上是否正确保存在那里?
  • 您使用 getItem() 错误。它返回值。 if (localStorage.getItem("local") == whatever etc..
  • 阅读getItem的文档
  • 这不是一个问题标题,而是一系列标签...请阅读How to Ask,尤其是关于写好标题的部分。
  • 每个人都认为您正在尝试存储输入的值,但您能否为我们澄清一下。你到底想存储什么?您是否熟悉 localStorage 的工作原理(特别是关于序列化以及如何写入/覆盖数据)?您期望能够检索什么以及多少数据?在这里告诉我们更多关于你的最终目标。

标签: jquery html css function local-storage


【解决方案1】:

更新

演示1

“我的主要目标是即使刷新页面后卡片也会淡出。我似乎无法让它工作。”

这在问题中并不明显,但现在已经澄清了,首先我应该通知您localStorage,因为它与您的情况有关:

  • localStorage 将数据无限期地存储为字符串(直到用户使用clear() 将其完全清除,或removeItem() 方法,或通过使用setItem() 和新值覆盖现有键,或超出了 2 到 10MB 的限制)。

  • localStorage 存储限制是每个域。例如,site-x.com 有 2MB 数据,剩余 8MB,site-z.net 有 4MB 存储数据,剩余 6MB。此外,为一个域存储的内容不与任何其他域共享。

  • 作为有益的“副作用”,localStorage 中的数据在域的所有页面之间共享。

顺便说一句,关于 OP (O原始 OP 有两点需要指出>Post):

var storage = $(".card-1").val;

语法上是错误的,应该如下(假设.card-1 是一个表单控件,如&lt;input&gt;&lt;textarea&gt;):

var storage = $(".card-1").val()

其次,&lt;section&gt; 是块元素而不是表单控件,因此val() 方法和.value 属性将永远无法工作。了解一个元素是否为表单控件的最简单方法是它可以具有value 属性。

此演示无法在此站点上运行,因为 localStorage 已被阻止。请参阅此 PLUNKER 1PLUNKER 2

演示1

<!DOCTYPE html>
<html>

<head>
  <style>
    body {
      font: 400 16px/1.5 Verdana;
    }
    
    [type=checkbox] {
      display: none;
    }
    
    #chx0:checked~.card-0 {
      display: none;
    }
    
    #chx1:checked~.card-1 {
      display: none;
    }
    
    #chx2:checked~.card-2 {
      display: none;
    }
    
    label,
    input {
      font-family: Consolas;
      font-variant: small-caps;
      font-size: 20px;
      display: block;
      cursor: pointer;
    }
    
    label {
      min-height: 30px;
      background: rgba(0, 200, 0, 0.4);
      text-align: center;
      padding-top: 8px;
    }
    
    code {
      font-family: Courier New;
      background: rgba(121, 45, 121, 0.2);
    }
    
    kbd {
      border: 2px outset grey;
      border-radius: 8px;
      padding: 2px 4px;
      font-family: Verdana;
    }
    
    footer {
      height: 90px;
    }
    
    summary h3 {
      display: inline-block;
      cursor: pointer;
      margin: 10px auto;
    }
  </style>
</head>

<body>
  <details>
    <summary>
      <h3>CSS</h3>
    </summary>
    <ul>
      <li>Click one of the <code>&lt;fieldset&gt;s</code> and it disappears because...
        <ul>
          <li>
            there's a nested <code>&lt;label&gt; [for="ID-of-Input"]</code> linked to an...
          </li>
          <li>
            invisible <code>&lt;input id="ID-of-Input"&gt; [type=checkbox]</code>
          </li>
        </ul>
      </li>
      <li>
        A click on a <code>&lt;label&gt;</code> will be a click on its linked input
      </li>
      <li>
        By using the pseudo-class selector <code>:checked</code> and the general sibling combinator <code>~</code> the "younger" siblings are now subject to a switch that can manipulate CSS dramatically around them and on them. In the demo, each invisible
        checkbox will hide a specific <code>.card</code>.
      </li>
    </ul>
  </details>
  <details>
    <summary>
      <h3>jQuery</h3>
    </summary>
    <ul>
      <li>
        Basically CSS is used to remove the targets and jQuery is used tp keep the current state of certain elements persistant.
      </li>
      <li>
        In the demo an <code>each()</code> will loop through the checkbox <code>#id</code>s and pass them through <code>getData()</code> function as keys. If any values of '1' are found, the checkbox <code>#id</code> that corresponds with the key gets
        checked.
      </li>
    </ul>
  </details>
  <h3>Instructions</h3>
  <p><kbd>Reload</kbd> this page and the cards that are gone continue to be so. In order to remove the data from <code>localStorage</code>, click the <kbd>Clear</kbd> button.</p>
  <hr>

  <input id='chx0' class='chx' type='checkbox'>
  <input id='chx1' class='chx' type='checkbox'>
  <input id='chx2' class='chx' type='checkbox'>

  <fieldset class='card-0 card' data-id='chx0'>
    <label for='chx0'>Card 0</label>
  </fieldset>
  <hr>
  <fieldset class='card-1 card' data-id='chx1'>
    <label for='chx1'>Card 1</label>
  </fieldset>
  <hr>
  <fieldset class='card-2 card' data-id='chx2'>
    <label for='chx2'>Card 2</label>
  </fieldset>

  <input class='reload' type='button' value='Reload' style='float:left; margin:5px 10px 20px 0; width:20ch;background:cyan;color:#000'>
  <input class='clear' type='button' value='Clear' style='float:right; margin:5px 10px 20px 0; width:20ch;background:tomato;color:#fff'>

  <footer>&nbsp;</footer>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    var data;

    $('.chx').each(function(i, c) {
      var key = this.id;
      data = getData(key);
      console.log(data);
      if (data === '1') {
        this.checked = true;
      }
    });

    $(".chx").on('click', function() {
      var key = this.id;
      var val = this.checked ? '1' : '0';
      setData(key, val);
    });

    function getData(key) {
      data = localStorage.getItem(key);
      if (data === null) {
        return false;
      } else {
        return data;
      }
    }

    function setData(key, value) {

      if (key === undefined || value === undefined) {
        return false;
      } else {
        localStorage.setItem(key, value);
        return true;
      }
    }

    $('.reload').on('click', function() {
      location.reload(true);
    });

    $('.clear').on('click', function() {
      localStorage.clear();
    });
  </script>
</body>

</html>


演示 2

你有一个语法错误$(".card-1").val; 应该是$(".card-1").val()。除此之外,我还没有费心去调试其余的东西。不要在我只能假设为&lt;input&gt; 的地方使用点击事件(测试按钮的值会很不方便),使用更改或输入事件(如果处理localStorage,我建议更改)。下面的演示以localStorage 的简单使用为特色。

此演示无法在此站点上运行,因为 localStorage 已被阻止。请参阅此 PLUNKER 1PLUNKER 2

演示2

var data = getData('card-1');

console.log(data);

if (data) {
  $('.card-1').val(data);
}

$(".card-1").on('change', function() {
  var storage = $(this).val();
  setData.call(this, 'card-1', storage);
  $(this).fadeOut();
});

function getData(key) {
  var data = localStorage.getItem(key);
  if (data === null) {
    return false;
  } else {
    return data;
  }
}

function setData(key, value) {
  if (key === undefined || value === undefined) {
    return false;
  } else {
    localStorage.setItem(key, value);
    return true;
  }
}

$('.view').val('card-1: ' + data);
$('.clear').on('click', function() {
  localStorage.clear();
})
<!DOCTYPE html>
<html>

<head>

</head>

<body>
  <ol>
    <li>Enter text then click the <kbd>BLR</kbd> button to unfocus from the input thereby triggering the change event.</li>
    <li>Next, refresh this page and the text entered should be in the input again.</li>
    <li>In order to remove the text from localStorage, click the <kbd>CLR</kbd> button.</li>
  </ol>

  <input class='card-1' value=''>
  <input class='blur' type='button' value='BLR'>
  <input class='clear' type='button' value='CLR'>

  <output class='view'></output>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

</body>

</html>

【讨论】:

    【解决方案2】:

    首先,您只想在点击时淡出卡片(每个卡片由一个部分 HTML 标记表示),所以

    $("section").click(function() {
      var card = $(this);  //get the card that is clicked
      var storage = card.attr("class");  //get the class name of this card
      card.fadeOut();  //hide it
      localStorage.setItem("local", storage);  //save the value
    });
    

    接下来,您会希望页面检查是否有任何储值,以便您可以隐藏卡片。

    $(function() {  //short hand for $(document).ready()
      var value = localStorage.getItem("local");  //get the value from local storage with the same key, which is "local"
      if (value) {  //if there is a value stored previously
        $("section." + value).fadeOut();  //get back the same card and hide it
      }
    });
    

    【讨论】:

    • 感谢您的回答。如果我有一个部分而不是输入,我该怎么办?
      那么我不能使用 .val 吗?使用您的代码,该功能可以工作,但刷新页面后卡片仍然显示
    • 正如我所说,我为我的卡使用一个部分而不是输入。如何在不使用 .val 选项的情况下访问元素(类)值?我可以只使用 (".card-1").css 访问它吗?非常感谢您的回答!
    • 如果您可以显示卡片的区别,那么只有我能够为您的案例提供帮助,因为您似乎试图隐藏卡片而不知道卡片之间的区别是什么牌。两张卡片的 HTML sn-p 会很有帮助
    • 我有五张不同类别的卡片。当您单击 .card-1 时,我希望该卡在您单击 .card-2 时淡出并保存在 localstorage 中,我希望将其淡出并保存到 localstorage 。卡片看起来像这样

      内容

      内容

    • 根据您卡片的 HTML sn-p 更新了我的答案
    猜你喜欢
    • 1970-01-01
    • 2016-06-17
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2023-03-29
    • 2016-04-29
    • 2018-10-02
    • 2018-11-05
    相关资源
    最近更新 更多