[英]Javascript : hide and show toggle button on <td> restores while page is loading
我有這樣一個場景,在我的jsp頁面中有一個普通的 < table > < td > 標簽,一旦單擊 <a href..> 超鏈接,我需要在它們之間切換 hide-n-show。 我使用純 javascript function(不是 jQuery)進行了切換,它工作正常。
但我面臨的問題是,在 < td > 中執行某些操作時,它用於重新加載頁面,因此它正在重置切換的 state。
jsp 中的代碼(帶有custom-tag )是:
<a id="toggleLinkId" href="#" onclick="javascript:toggleTable();" >Toggle Table</a>
<td colspan="2" id="id1" style="display: none">
<query:SingleQueryRecord editUrl="<%=editURL%>" extraparameters='<%=searchURL%>'/>
</td>
<td colspan="2" id="id2" >
<query:QueryDataTable editUrl="<%=editURL%>" />
</td>
在這里,一旦單擊“ toggleLinkId
”鏈接,它就會調用 javascript function“ toggleTable()
”。 但是在進行操作之后,它會重新加載並重置切換的 < td >,因為第一次加載頁面需要“ style="display: none"
'。
我寫的javascript是一個簡單的:
function toggleTable(){
if( document.getElementById('id1').style.display == 'none' ){
document.getElementById('id2').style.display = 'none';
document.getElementById('id1').style.display = 'block';
} else{
document.getElementById('id1').style.display = 'none';
document.getElementById('id2').style.display = 'block';
}
}
希望我state能說清楚我的問題。 如果您有任何建議可以在頁面重新加載后保留切換的 state,那將非常有幫助。 謝謝。
我制作了一個 LocalStorage 示例。 希望對您有所幫助
// First check if there is data saved in localStorage
var retrievedData = localStorage.getItem("localStorageMyData");
// ...and if there is data execute them
if (retrievedData) {
var myValue = JSON.parse(retrievedData);
var id1 = myValue.id1;
var id2 = myValue.id2;
document.getElementById('id1').setAttribute('style', id1);
document.getElementById('id2').setAttribute('style', id2);
}
function toggleTable() {
if (document.getElementById('id1').style.display == 'none') {
document.getElementById('id2').style.display = 'none';
document.getElementById('id1').style.display = 'block';
} else {
document.getElementById('id1').style.display = 'none';
document.getElementById('id2').style.display = 'block';
}
// The information is saved in localStorage with each click
var id1 = document.getElementById('id1').getAttribute("style");
var id2 = document.getElementById('id2').getAttribute("style");
var myValue = ({ id1: id1, id2: id2 });
localStorage.setItem("localStorageMyData", JSON.stringify(myValue));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.