javascript - 隐藏/显示特定内容并保存为 localStorage

标签 javascript jquery local-storage bootstrap-switch

我正在寻找使用引导开关到 toggle要隐藏和显示的特定内容,取决于是否选中。我想在本地存储中保存此复选框的状态。我是 javascript 的新手,无法弄清楚。如果能提供任何帮助,我将不胜感激......

The jsfiddle is self-explanatory .我也会在这里粘贴代码。谢谢!

<div class="well text-center">
  <h1>Today's Games</h1>
  <br>
  <input type="checkbox" name="spoiler-checkbox" data-size="mini" data-on-color="danger">
  <br />
  <label for="checkbox">Spoiler-Free</label>
</div>

<div class="col-xs-4 col-xs-offset-4">
  <table class="table table-bordered" id="Game1">
    <thead>
      <tr>
        <th class="status" colspan="3" id="timeleft">3:31 3rd Quarter</th>
        <th class="status" colspan="3" id="starttime">7:30pm EST</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td class="team" colspan="2">Bulls</td>
        <td class="score" colspan="1">59</td>
      </tr>
      <tr>
        <td class="team" colspan="2">Bucks</td>
        <td class="score" colspan="1">65</td>
      </tr>
    </tbody>
  </table>
</div>
#timeleft {
    color:red;
}

#starttime {
    display:none;
}

.team {
    font-weight: 700;
}
$("[name='spoiler-checkbox']").bootstrapSwitch();

更新:

K,在多个来源的帮助下,我让它工作得很好。不是最干净的代码,但完全符合我的要求。

http://jsfiddle.net/j9knzuh1/28/

最佳答案

是的,您可以使用带有 set 和 get 方法的 localStorage 完美地保存和检索状态。只需在 switchChange.bootstrapSwitch 上放置一个监听器,并在每次更改时将值存储在 localStorage 上,然后在每次加载页面时进行简单的验证以查看如果 localStorage 中存储了任何值。

请注意,值存储为字符串,因此,应将它们转换回其类型,在本例中为 bool 值。 这是您更新的完整 fiddle :http://jsfiddle.net/j9knzuh1/24/

$( document ).ready(function() {


//Set the listener to store data on localstorage whenever event switch is fired
    $("[name='spoiler-checkbox']").on('switchChange.bootstrapSwitch', function(event, state) {
        if (localStorage)
        localStorage.setItem("ckbspoiler", state); //ckbspoiler is just the name you want
    });



// retrieve the localstorage value for ckbspoiler and set the last saved status if any
var lastState = null;
if (localStorage)
    lastState = (localStorage.getItem("ckbspoiler")  === "true"); //Notice we are using this to convert it to its natural type: boolean

//If there was a lastState saved, then update the checkbox status        
if(lastState != null)  $("[name='spoiler-checkbox']").prop('checked', lastState);


$("[name='spoiler-checkbox']").bootstrapSwitch();




 });

关于javascript - 隐藏/显示特定内容并保存为 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32672764/

相关文章:

javascript - 电话号码正则表达式验证

javascript - 在同一窗口中使用 localStorage 监听变化

javascript - 如何用 Sentry 报告console.error?

javascript - 动态返回配置值(node.js)

javascript - Angular 4路由器导出CSS

javascript - 使用 jQuery 测试 html lang 属性

jquery - Bootstrap 模态不会显示在视频元素上

javascript - 更改 materializeCSS card-reveal 的 overflow on clicking an element contained in card

reactjs - REACT - 使用 localstorage 更新组件

javascript - localStorage 事件监听器不会在 Chrome 中为本地文件触发