簡體   English   中英

如何保持多個狀態<details>頁面刷新期間頁面上的元素?

[英]How to keep the state of multiple <details> elements on page during a page refresh?

我有一個包含多個細節元素的頁面,我對通過 localStorage/sessionStorage 保持每個細節元素的狀態很感興趣。 因此,如果用戶打開多個詳細信息元素,然后導航到新頁面,然后又返回原始頁面,則他們最初打開的詳細信息元素將保持打開狀態。 任何關於最好的方法的幫助將不勝感激。 謝謝!

您可以將id添加到每個 detail 元素,並使用事件toggle將其狀態保存在 localStorage 中。

然后在頁面加載時,在 localStorage 上運行並添加open到每個細節

JSFiddle

 (function() { $('details').on('toggle', function(event) { var id = $(this).attr('id') var isOpen = $(this).attr('open') console.log(id, isOpen) window.localStorage.setItem('details-'+id, isOpen) }) function setDetailOpenStatus(item) { if (item.includes('details-')) { var id = item.split('details-')[1]; var status = window.localStorage.getItem(item) if (status == 'open'){ $("#"+id).attr('open',true) } } } $( document ).ready(function() { for (var i = 0; i < localStorage.length; i++) { setDetailOpenStatus(localStorage.key(i)); } }); })();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <details id='1'> <summary>System Requirements 1</summary> <p>Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended.</p> </details> <details id='2'> <summary>System Requirements 2</summary> <p>Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended.</p> </details> <details id='3'> <summary>System Requirements 3</summary> <p>Requires a computer running an operating system. The computer must have some memory and ideally some kind of long-term storage. An input device as well as some form of output device is recommended.</p> </details>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM