是否有重新加载页面后打开/显示div?

时间:2018-01-22 11:32:12

标签: javascript jquery twitter-bootstrap-3

我想在重新加载页面后打开一个模态窗口。我打算在div中打开该模态。在页面加载后有没有办法打开div?

1 个答案:

答案 0 :(得分:0)

如果您不想仅使用javascript,则可以使用 url哈希参数

想法是当页面首次加载 js 时会向网址添加一个字词,所以当页面重新加载时 js 会看到该字词在url中,我们将知道该页面已重新加载以及有多少时间。

<强>像

&#13;
&#13;
var url = window.location.href;
var hash = url.split('#')[1];
var recount;
if(hash != null){
recount = parseInt(hash.split('-')[1])+1;
hash = hash.split('-')[0];
}
if (hash == "re") {
	var elm = document.getElementById("first");
	elm.innerHTML = "the page has been reloaded ("+recount+")";
    window.location.href = url.split('#')[0] + "#re-"+recount;
//alert("the page has been reloaded ("+recount+")");
} else {
    window.location.href += "#re-0";
}
&#13;
<body>
	<button onclick="location.reload()">Reload</button>
	<div id ="first">first page</div>
</body>
&#13;
&#13;
&#13;

之后添加 bootstrap jquery

&#13;
&#13;
var url = window.location.href;
var hash = url.split('#')[1];
var recount;
if(hash != null){
recount = parseInt(hash.split('-')[1])+1;
hash = hash.split('-')[0];
}
if (hash == "re") {
	$("#first").hide();
	$("#modal_text").html("the page has been reloaded ("+recount+")");
	$("#myModal").modal();
    window.location.href = url.split('#')[0] + "#re-"+recount;
    
} else {
    window.location.href += "#re-0";
}
&#13;
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

	<button onclick="location.reload()">Reload</button>
	<div id ="first"><h1>first page</h1></div>
	<!-- Modal -->
	  <div class="modal fade" id="myModal" role="dialog">
	    <div class="modal-dialog">
	    
	      <!-- Modal content-->
	      <div class="modal-content">
	        <div class="modal-header">
	          <button type="button" class="close" data-dismiss="modal">&times;</button>
	          <h4 class="modal-title">Modal Header</h4>
	        </div>
	        <div class="modal-body">
	          <p id='modal_text'></p>
	        </div>
	        <div class="modal-footer">
	          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
	        </div>
	      </div>
	      
	    </div>
	  </div>
	  

</body>
&#13;
&#13;
&#13;

但我建议使用Cookie或localStorage 最佳方式