我的 localStorage
存在问题,即使一个部分已关闭但另一部分应该保留,它也会记住所有保存。示例:页面上有两个横幅。如果一个人单击关闭横幅,它将关闭该横幅,但也会记住另一个横幅也已关闭。
代码:
<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>
最佳答案
您应该使用 id 进行存储,而不是简单地将同一变量“isHide”设置为 true 或 false。
例如设置为存储:localStorage.setItem('isHide-1561524897', true);
并读取它: localStorage.getItem('isHide-1561524897');
关于javascript - 如何在每个项目上而不是所有项目上使用 localStorage 进行保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56765625/