从复选框状态存储和使用Cookie

时间:2018-01-04 16:32:05

标签: javascript jquery

请您查看一下这段代码,如果用户选中了checkbox,请告诉我如何使用JS Cookie不显示弹出窗口?

setTimeout(function() {
  $("#myModal").modal('show');
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
      <div class="pull-left"><input id="checkBox" type="checkbox"> No Display Next Times</div>
           <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

这对我有用,虽然cookie部分似乎只能在Firefox上运行。我似乎无法在Chrome中设置Cookie ...安全设置可能?

<script>

setTimeout(function() {
  // Read cookie
  var show = getCookie('show');

  // Check cookie value
  if(show == 1 || show == '')
    $("#myModal").modal('show');
}, 1000);


// This runs when the modal window is hidden
$('#myModal').on('hidden.bs.modal', function (e) {

  // Save check box to cookie
  if(document.getElementById("mycheckBox").checked) {
    document.cookie = "show=0";
  } else {
    document.cookie = "show=1";
  }

})

// Nice function to read a specific cookie value
function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) 
    return parts.pop().split(";").shift();
  else
    return '';
}

</script>