3

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

jsfiddle 是不言自明的。我也会在这里粘贴代码。非常感谢你!

<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/

4

1 回答 1

2

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

请注意,值存储为字符串,因此应将它们转换回其类型,在本例中为布尔值。这是您更新的完整小提琴: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();




 });
于 2015-09-19T21:30:19.173 回答