我根据 cookie 的值插入和删除 div。通过选中和取消选中复选框来更新 cookie 的值。这对于单个选项卡来说效果很好。 但是如果为同一页面打开多个选项卡,如何更新其他选项卡中的 div。 cookie 值会更新,因为它对于浏览器而言保持不变,但如何根据 cookie 值添加或删除 div。
最佳答案
如果您同意使用本地存储而不是 Cookie,则可以使用 storage
事件,该事件会在对本地存储进行更改时触发。
参见http://synccheckbox.site44.com/一个运行的例子。代码粘贴如下:
<!doctype html>
<html>
<head>
<style>html { font-family:Arial }</style>
</head>
<body>
This checkbox should synchronize between open tabs:
<input type="checkbox" id="checkbox" />
<script>
function updateCheckbox() {
document.getElementById('checkbox').checked =
(localStorage.checked === 'true');
}
updateCheckbox();
document.getElementById('checkbox').addEventListener('change', function () {
localStorage.checked = this.checked;
});
window.addEventListener('storage', function () {
updateCheckbox();
});
</script>
</body>
</html>
关于javascript - 根据多个选项卡中的cookie更新div元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37804020/