【问题标题】:How to save using localStorage on each item and not for all如何在每个项目而不是所有项目上使用 localStorage 进行保存
【发布时间】:2019-11-07 23:24:55
【问题描述】:

我对@9​​87654321@ 有一个问题,即使一个部分已关闭但另一个部分应该保留,它也会记住所有保存。示例:页面上有两个横幅。如果一个人单击关闭横幅,它将关闭该横幅,但也会记住另一个横幅也已关闭。

代码:

<section class="alert-notice-contain status-alerts">

<div id ="1561524897" class="type-notice relative">
    <div class="close-notice-alert"></div>
    <div class="status-contain">
        <div class="status-msg">
            <p>This is a test. This is a long test.</p>
        </div>
    </div>
</div>

<div id ="1561524873" class="type-notice relative">
    <div class="close-notice-alert"></div>
    <div class="status-contain">
        <div class="status-msg">
            <p>This is notice 1</p>
        </div>
    </div>
</div>

<script> // JS code (inline to get the dynamic #ID
( function( $ ) {
        'use strict';
        $( document ).on( 'ready', function() {
            // Status
if(localStorage.getItem('isHide'))
$('#1561524897').hide();
$('#1561524897 .close-notice-alert').click(function(){
$('#1561524897').hide();localStorage.setItem('isHide',true);
});
} );
} ( jQuery ) );
</script>

<script>
    ( function( $ ) {
        'use strict';
        $( document ).on( 'ready', function() {
            // Status
if(localStorage.getItem('isHide'))
$('#1561524873').hide();
$('#1561524873 .close-notice-alert').click(function(){
$('#1561524873').hide(); localStorage.setItem('isHide',true);});
} );
} ( jQuery ) );
</script>

</section>

【问题讨论】:

  • 使用对象(和JSON.stringify()JSON.parse())来存储横幅的可见性。

标签: javascript php jquery local-storage


【解决方案1】:

您应该使用 id 进行存储,而不是简单地将相同的变量 'isHide' 设置为 true 或不设置。 例如设置为存储:localStorage.setItem('isHide-1561524897', true); 并阅读:localStorage.getItem('isHide-1561524897');

【讨论】:

  • 是的。从字面上看,在我提交问题后,答案就在梦中出现了。谢谢。
【解决方案2】:

使用对象存储在本地存储中。 JSON.stringify() 将您的对象转换为字符串形式,JSON.parse() 从本地存储获取后将字符串转换为对象形式。 例如。

obj = { visibility : 'hidden' }

// set the localstorage
localstorage.setItem('isHide', JSON.stringify(obj));

// get the localstorage
let storageValue = JSON.parse(localstorage.getItem('isHide'));
// use storageValue accordingly 

【讨论】:

  • 您的回答并没有解决问题,因为所有元素仍然只有一种状态。
猜你喜欢
  • 1970-01-01
  • 2017-03-17
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
  • 2023-03-12
相关资源
最近更新 更多