我是 Javascript 新手,我有一个用于 html 表的 Javascript,用户可以编辑该表以显示或隐藏 html 表中的列。脚本运行良好。但问题是,当刷新页面时,它会显示 html 表中的所有列。它不记得最后的设置。
我希望能够存储脚本中上次操作的设置,因此当刷新或加载页面时,它会记住上次设置。我不知道如何实现这一目标,如果您能告诉我如何做到这一点,我将不胜感激?
这是 JavaScript:
请参阅 jsfiddle https://jsfiddle.net/b9chris/HvA4s/ 的工作示例
<script>
$(document).ready(function(){
$('#edit').click(function() {
var headers = $('#table th').map(function() {
var th = $(this);
return {
text: th.text(),
shown: th.css('display') != 'none'
};
});
var h = ['<div id=tableEditor><button id=done>Done</button><table><thead><tr>'];
$.each(headers, function() {
h.push('<th><input type=checkbox',
(this.shown ? ' checked ' : ' '),
'/> ',
this.text,
'</th>');
});
h.push('</tr></thead></table></div>');
$('body').append(h.join(''));
$('#done').click(function() {
var showHeaders = $('#tableEditor input').map(function() { return this.checked; });
$.each(showHeaders, function(i, show) {
var cssIndex = i + 1;
var tags = $('#table th:nth-child(' + cssIndex + '), #table td:nth-child(' + cssIndex + ')');
if (show)
tags.show();
else
tags.hide();
});
$('#tableEditor').remove();
return false;
});
return false;
});
});
</script>
最佳答案
要在 javascript 中写入 cookie,请写入:
document.cookie = "username=John Doe";
您可以将 username 替换为您能想到的任何名称,= 后面的所有内容当然都是您的值。
要读取您的 cookie,您可以使用 W3Scools 的此功能:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
如果您想获取用户名,只需调用 getCookie("username")
关于javascript - 将设置存储在 Javascript Cookie 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42092999/