我在Safari 5.0中遇到了以下问题(不是在所有基于WebKit的浏览器中),此代码:
<html>
<script>
var onstorage = function(evt) {
alert([evt.key, evt.oldValue, evt.newValue].join('\n'));
}
var onclick = function(evt) {
localStorage.setItem('test', Math.random());
}
var oninit = function() {
//actually, it works the same way with old "plain event" onclick
document.querySelector('#test').addEventListener('click', onclick, false);
window.addEventListener('storage', onstorage, false);
}
</script>
<body onload="oninit()">
<input id="test" type="button" value="setting a random value"/>
</body>
如果我们点击按钮,
将触发警报。虽然这段代码 -
<html>
<script>
var onstorage = function(evt) {
alert([evt.key, evt.oldValue, evt.newValue].join('\n'));
}
var onclick = function(evt) {
localStorage.setItem('test', Math.random());
}
var oninit = function() {
window.addEventListener('storage', onstorage, false);
//actually, it works the same way with old "plain event" onclick
document.querySelector('#test').addEventListener('click', onclick, false);
}
</script>
<body onload="oninit()">
<input id="test" type="button" value="setting a random value"/>
</body>
触发很少的警报,如预期的那样。 我认为这是一个错误,但不能有人解释我 - 为什么只交换两行代码导致这种奇怪的行为?
答案 0 :(得分:1)
没有错误(虽然像其他人一样评论我不会将事件处理程序命名为名称可能会混淆的全局函数)。
问题是localStorage的通知如何工作。实质上,事件仅针对使用相同localStorage的其他窗口(或选项卡)触发。
这里是StackOverflow上的a similar question and answer。
因此,在您的示例中,存储更改事件不会触发:处理程序位于同一页面上。