【问题标题】:Saving multiple checkboxes values into localStorage将多个复选框值保存到 localStorage
【发布时间】:2017-05-05 18:06:29
【问题描述】:

我遇到的问题是复选框值没有改变。我错过了什么?感谢您的帮助!

html:

<input type="checkbox" name="smth1" />something1<br />
<input type="checkbox" name="smth2" />something2<br />
<input type="checkbox" name="smth3" />something3<br />
<br />

<input type="checkbox" name="anthr1" />anotherthing1<br />
<input type="checkbox" name="anthr2" />anotherthing2<br />
<input type="checkbox" name="anthr3" />anotherthing3<br />
<br />

<input type="checkbox" name="new1" />newthing1<br />
<input type="checkbox" name="new2" />newthing2<br />
<input type="checkbox" name="new3" />newthing3<br />
etc etc

脚本:

$("input[type=checkbox]").each(function() {
    var name = $(this).attr('name');

     if (localStorage.getItem(name) == "on") {
        $(this).prop('checked', true);
    }     
});

$("input[type=checkbox]").change(function() {

    var name = $(this).attr('name'),
    value = $(this).val();

    localStorage.setItem(name,value);                  
});

【问题讨论】:

  • value = $(this).val()更改为value = this.checked? 'on' : ''

标签: javascript jquery checkbox local-storage


【解决方案1】:

$(this).val();总是有“开”的价值。你应该使用

value = $(this).is(':checked') ? 'on' : 'off'

【讨论】:

    【解决方案2】:

    这可以做到value = $(this).is(':checked')localStorage.getItem(name) == "true"

    $("input[type=checkbox]").each(function() {
      var name = $(this).attr('name');
    
      if (localStorage.getItem(name) == "true") {
        $(this).prop('checked', true);
      }
    });
    
    $("input[type=checkbox]").change(function() {
    
      var name = $(this).attr('name'),
        value = $(this).is(':checked');
      localStorage.setItem(name, value);
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-17
      • 2021-12-07
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 2016-04-22
      相关资源
      最近更新 更多