计数页面重新加载并显示Bootstrap模式

时间:2018-01-18 08:45:16

标签: javascript html

我想计算F5(重新加载)次数并在3次时显示Bootstrap模态。 但是当我按下F5(3次)时页面没有响应。我该如何解决这个问题?

<script>
    var state = history.state || {};
    var times = 3; //set times
    var reloadCount = (state.reloadCount || 0) % times;

    if (performance.navigation.type === 1) { // Reload
        state.reloadCount = ++reloadCount;
        history.replaceState(state, null, document.URL);
    } else if (reloadCount) {
        delete state.reloadCount;
        reloadCount = 0;
        history.replaceState(state, null, document.URL);
    }

    if (reloadCount == 2) {
        //When reload ==2 show boostrap model.
        $('#exampleModal').modal('show');
    }   
</script>

我的html如下:

<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
      </div>
    </div>
  </div>
</div>

2 个答案:

答案 0 :(得分:0)

document.onkeydown = fkey;
document.onkeypress = fkey
document.onkeyup = fkey;

var wasPressed = false;

function fkey(e){
    e = e || window.event;
   if( wasPressed ) return; 

    if (e.keyCode == 116) {
         var counter = sessionStorage.getItem('reload') || 0;
         sessionStorage.setItem('reload', counter + 1);
         wasPressed = true;
    }
}

window.addEventListener('DOMContentLoaded', function (event) {
   var counter = sessionStorage.getItem('reload');
   if(counter === 3){
     $('#exampleModal').modal('show');
   }
});

答案 1 :(得分:0)

您的模态ID为exampleModalCenter,请尝试

$('#exampleModalCenter').modal('show');

确保在Bootstrap.js之前包含您的JQuery库。例如:

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/js/bootstrap.min.js" integrity="sha384-a5N7Y/aK3qNeh15eJKGWxsqtnX/wWdSZSKp+81YjTmS15nvnvxKHuzaWwXHDli+4" crossorigin="anonymous"></script>