2 回答

TA貢獻1836條經驗 獲得超13個贊
使用localStorage. 這會<p>在 body 中找到標簽元素,然后使用每個元素獲取 id 以供參考。
我嘗試在這里使用小提琴,但該網站對 localStorage 有安全投訴。
將此代碼復制/粘貼到文件中以嘗試一下。請注意,您可能需要更新moment.js此代碼中的引用以匹配您的文件路徑。
<!doctype html>
<html>
<head>
<title>localStorage example</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="moment.js"></script>
</head>
<body>
<div class='grid-container'>
<div class='item7'><p id='p0'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<div class='grid-container'>
<div class='item7'><p id='p1'>Sylus: </p></div>
<div class='item8'><img src='htts://i.i.com/k.jpg' onclick='cS(this)' /></div>
</div>
<script>
function cS(element) {
var pTag = element.parentElement.previousElementSibling.firstChild;
if (element.src == "htts://i.i.com/k.jpg")
{
element.src = "http://i.i.com/v.jpg";
var d = moment().format('dddd HH:mm');
var pText = 'Sylus: ' + d;
pTag.innertHTML = pText;
// Set (save) a reference to browser localStorage
localStorage.setItem(pTag.id, pText);
}
else
{
element.src = "htts://i.i.com/k.jpg";
pTag.innerHTML = "Sylus: ";
// Remove the stored reference. (delete this if not needed)
localStorage.removeItem(pTag.id);
}
}
$(document).ready(function() {
pElements = $('body').find('p').each(function(index, element) {
// Get the localStorage items. The retrieved <p> elements,
// we use their id value to reference the key in storage.
storageItem = localStorage.getItem(element.id);
if (storageItem) {
$('#' + element.id).text(storageItem);
}
});
});
</script>
</body>
</html>
單擊圖像后(需要替換為真實的圖像),打開瀏覽器的 Web 檢查器界面,單擊Storage選項卡,然后展開列表中的本地存儲(見下圖),然后選擇正在測試的文件。
將顯示鍵/值對。鍵是對<p>標簽 ID 的引用,值將具有標簽日期字符串,例如Sylus: Wednesday 22:28.
一旦您看到一個或兩個條目被設置為存儲,請關閉然后重新打開瀏覽器選項卡。具有日期的<p>元素應該從存儲中重新加載它們的值。
瀏覽器的 Local Storage 區域應該類似于下圖:
- 2 回答
- 0 關注
- 135 瀏覽
添加回答
舉報