本文介绍了不调用localStorage eventListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在窗口DOM-Object中添加了一个eventListener,并希望跟踪对localStorage所做的更改。

I added an eventListener to the window DOM-Object and want to keep track of the changes made to localStorage.

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>

    <script language="JavaScript"><!--
        window.addEventListener('storage', storageEventHandler, false);
        function storageEventHandler(evt){
            console.log("oldValue: " + evt.oldValue );
            console.log("storage event called key: " + evt.key );
            console.log("newValue: " + evt.newValue );

        }
        $(document).ready(function(event) {
            $('#link1').click(function(event){
                event.preventDefault();
                localStorage.setItem('page', 2000);
                console.log(localStorage.getItem('page'));
            });
            $('#link2').click(function(event){
                event.preventDefault();
                localStorage.setItem('page', 998);
                console.log(localStorage.getItem('page'));

            });

         });
    </script>
</head>
</html>

不管怎样,即使在我点击link1或link2时更改了localStorage值,也永远不会调用storageEventHandler。
非常感谢任何帮助。

Somehow the storageEventHandler is never called even though the localStorage value is changed when I click link1 or link2.Any help is much appreciated.

推荐答案

有些浏览器不支持存储事件和大多数浏览器支持它的只会在通过不同的窗口更改存储时调用它。所以,在两个窗口中打开你的页面。单击一个窗口中的链接,您可能会在另一个窗口中看到该事件。

Some browsers don't support the storage event, and most of the browsers that do support it will only call it when the storage is changed by a different window. So, open your page up in two windows. Click the links in one window and you will probably see the event in the other.

假设您的页面已经知道在其自己的窗口中与localStorage的所有交互,只有在不同的窗口改变时才需要通知。当然,这是一个愚蠢的假设。但是,localStorage是一个新事物。希望他们最终能够全力以赴。

The assumption is that your page will already know all interactions with localStorage in its own window and only needs notification when a different window changes things. This, of course, is a foolish assumption. But, localStorage is a new thing. Hopefully, they'll eventually figure it all out.

这篇关于不调用localStorage eventListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 01:38