保持选中复选框

时间:2015-08-20 10:01:13

标签: javascript html

我正在制作一个html页面,可用于通过手动点击复选框跟踪您观看的内容,以便了解您所在的剧集。我的问题是在离开页面并返回它后保持盒子检查,我一直在尝试使用cookie,但到目前为止还没有工作。我在谷歌浏览器上使用此功能,但不确定这是否有所作为。

    <h2>Season 1</h2>
<ul>
  <li><input type="checkbox" id="option1"/>Episode 1</li>
  <li><input type="checkbox" id="option2"/>Episode 2</li>
  <li><input type="checkbox" id="option3"/>Episode 3</li>
  <li><input type="checkbox" id="option4"/>Episode 4</li>
  <li><input type="checkbox" id="option5"/>Episode 5</li>
  <li><input type="checkbox" id="option6"/>Episode 6</li>
</ul>

这是我使用的Javascript代码:

        <script>
  function handleButtonClick(button){
    if ($(button).text().match("Check all")){
      $(":checkbox").prop("checked", true)
    } else {
      $(":checkbox").prop("checked", false)
    };
    updateButtonStatus();
  }
  function updateButtonStatus(){
    var allChecked = $(":checkbox").length === $(":checkbox:checked").length;
    $("button").text(allChecked? "Uncheck all" : "Check all");
  }
  function updateCookie(){
    var elementValues = {};
    $(":checkbox").each(function(){
      elementValues[this.id] = this.checked;
    });
    elementValues["buttonText"] = $("button").text();
    $.cookie('elementValues', elementValues, { expires: 7, path: '/' })
  }
  function repopulateFormELements(){
    var elementValues = $.cookie('elementValues');
    if(elementValues){
      Object.keys(elementValues).forEach(function(element) {
        var checked = elementValues[element];
        $("#" + element).prop('checked', checked);
      });
      $("button").text(elementValues["buttonText"])
    }
  }
  $(":checkbox").on("change", function(){
    updateButtonStatus();
    updateCookie();
  });
  $("button").on("click", function() {
    handleButtonClick(this);
    updateCookie();
  });
  $.cookie.json = true;
  repopulateFormELements();
</script>

以下是完整文档的链接:http://jsfiddle.net/r4gqqd0c/ 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

如果您不想使用数据库存储复选框状态,则可以使用localstorage。一个例子如下:

&#13;
&#13;
C1   C2      C3   C4
157 Job157  158 Illumina Parking Building 1 

158 Job157  158 Illumina Parking Building 1 
&#13;
//add this when a checkbox is clicked
$(":checkbox").on("click", function() {
  localStorage.setItem($(this).attr("id"), $(this).prop("checked"));
});
//when page loads
$(":checkbox").each(function() {
  var status = localStorage.getItem($(this).attr("id"));
  $(this).prop("checked", status === "true" ? true : false);
});
&#13;
&#13;
&#13;

fiddle

<强>参考文献:

Window.localStorage

Storage.getItem()

相关问题