2017-02-09 212 views
-1

我有一個要求,當點擊一個按鈕時,頁面需要重新加載。重新加載後,我需要顯示隱藏的div。如何在頁面重新加載後顯示隱藏的div?

下面是我的要求,它描述了我的問題?

1.在我的html代碼中包含一些帶有按鈕的文本,並且在此頁面中只有默認情況下我隱藏了一些文本div 2.當點擊按鈕時,我正在重新加載頁面。顯示隱藏的div

<!DOCTYPE html> 
 
<html> 
 
    <head> 
 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
 
    <script> 
 
     $(document).ready(function(){ 
 
     $("#test2").css("visibility","hidden"); 
 
     alert("reloaded"); 
 

 
     $("#p1").click(function(){ 
 

 
      setTimeout(function(e){ 
 
      alert("inside time out"); 
 
      $("#p2").css("visibility","visible"); 
 
      },3000); 
 
      location.reload(); 
 

 
     });  
 
     }); 
 
    </script> 
 
    </head> 
 
    <body> 
 

 
    <div id="myDiv"> 
 
     <p id="p1">This is sample text</p> 
 
    </div> 
 

 
    <div id="test2"> 
 

 
     <p id="p2">this is invisible text</p> 
 
    </div> 
 

 
    </body> 
 
</html>

在此先感謝

+0

我會通過添加按鈕,你的代碼,因爲你的要求是啓動按鈕,點擊後頁面重新加載。 –

+0

您可以使用cookie或hash,網絡存儲 – Laurianti

+0

Suresh,爲什麼你沒有接受任何問題的答案? –

回答

2

可以當用戶點擊該按鈕設置localStorage項目,並在頁面LOA d查找localStorage項目並有條件地顯示隱藏的div。

var $hidden = $('.hidden'); 
 

 
localStorage.getItem('show') && $hidden.show(); 
 

 
$('button').on('click',function() { 
 
    localStorage.setItem('show',true); 
 
    window.location.reload(false); 
 
})
.hidden { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="hidden">hidden</div> 
 
<button>click</button>

1

首先,如果你的要求是已經被點擊一個按鈕,你需要一個按鈕,而不是一個段落。

接下來,代替visibility屬性(即使在未顯示元素的情況下仍然在元素的頁面上分配空間),請使用display(不會)。

最重要的是,如果您重新加載文檔,那麼您擁有的任何局部變量將會丟失。您需要在頁面加載之間持續某種「標誌」。這可以通過多種方式完成(cookie,sessionStorage,localStorage,服務器端),但localStorage可能是最簡單的。

此代碼實際上不會在堆棧溢出片段的環境中運行,在這裏由於沙盒,但你可以看到它的here工作版本。

查看其它評論在線:

$(document).ready(function(){ 
 

 
     // Check to see if this is a page reload or not by seeing if a value was placed 
 
     // into localStorage from a previous page load 
 
     if(localStorage.getItem("loadedEarlier")){ 
 
      // Page has already loaded earlier 
 
      $("#test2").css("display","block"); 
 
     } 
 
     
 
     $("#btn").click(function(){ 
 
      location.reload(); 
 
     });  
 
     
 
     // Place a value into localStorage 
 
     localStorage.setItem("loadedEarlier", "yes")   
 
});
/* No need for JavaScript to initially hide the element which 
 
    can cause the usre to see it momentarially before the JS runs. 
 
    Set its default display to none instead.      */ 
 
#test2 { display:none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<button id="btn">Click to Reload</button> 
 
<div id="test2"><p id="p2">this is invisible text</p></div>

相關問題