Javascript 动态展开按钮的持久状态
如果你点击Javascript 动态展开按钮的持久状态,javascript,jquery,persistence,local-storage,Javascript,Jquery,Persistence,Local Storage,如果你点击,我有Javascript函数来显示内容。 但刷新页面后,所有内容都被隐藏。我想记住最后一个动作——缓存它 请帮忙 $(document).ready(function() { $("#button1, #button2, #button3").hide(); $("#news1").click(function() { $("#button1").show(); $("#button2
,我有Javascript函数来显示内容。
但刷新页面后,所有内容都被隐藏。我想记住最后一个动作——缓存它
请帮忙
$(document).ready(function() {
$("#button1, #button2, #button3").hide();
$("#news1").click(function() {
$("#button1").show();
$("#button2, #button3").hide();
});
$("#news2").click(function() {
$("#button2").show();
$("#button1, #button3").hide();
});
$("#news3").click(function() {
$("#button3").show();
$("#button1, #button2").hide();
});
});
你可以用locastorage<代码>本地存储将在http调用之间保持。因此,您将能够轻松地保持该状态。我还更新了您的代码,以遵循最佳实践 下面是HTML:
<input id="button1" type="button" class="expand" value="b1">
<input id="button2" type="button" class="expand" value="b2">
<input id="button3" type="button" class="expand" value="b3">
<input class="news" type="button" data-id="1" value="n1">
<input class="news" type="button" data-id="2" value="n2">
<input class="news" type="button" data-id="3" value="n3">
您可以找到完整的工作示例对服务器使用会话存储、本地存储或xhr。我不知道如何做,但我必须使用Javascript。
(function () {
function resetLocalStorage() {
$('.expand').each(function () {
delete localStorage[$(this).attr('id')];
});
}
$(".expand").each(function () {
if (localStorage.hasOwnProperty($(this).attr('id'))) $(this).show();
else if (localStorage.hasOwnProperty('trackingIsOn')) $(this).hide();
});
$(".news").click(function () {
$('.expand').hide();
var buttonElem = $('#button' + $(this).data('id'));
buttonElem.show();
resetLocalStorage();
localStorage[buttonElem.attr('id')] = true;
localStorage.trackingIsOn = true;
});
})();