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 关注
- 143 浏览
添加回答
举报