ContentEditable HTML5 localStorage有时不起作用

时间:2013-02-05 19:08:54

标签: javascript jquery ajax html5

我尝试使用本演示中的“ContentEditable”获取我网站的3个div:

http://html5demos.com/contenteditable

我还从此演示中加载了事件监听器

的h5utils.js

例如,其中一个div看起来像这样:

<div class="statsWrapper">
    <header id="met30" contenteditable="true" class="Tester">
</header>
    <p class="statsmonth_tester">
       Tester Overall
    </p>
</div>

html中的我的脚本

        <script>
        //Script for saving Content Sales Report to local storage//

        var editableTester = document.getElementById('met30');
        var editableSubscriber = document.getElementById('met32');
        var editableReadOnly = document.getElementById('met35');

        addEvent(editableTester, 'blur', function() {
            localStorage.setItem('Tester', this.innerHTML);
            document.designMode = 'off';                
        });

        addEvent(editableSubscriber, 'blur', function() {
            localStorage.setItem('Subscriber', this.innerHTML);
            document.designMode = 'off';
        });

        addEvent(editableReadOnly, 'blur', function() {
            localStorage.setItem('ReadOnly', this.innerHTML);
            document.designMode = 'off';
        });

        addEvent(editableTester, 'focus', function() {
            document.designMode = 'on';
        });
        addEvent(editableSubscriber, 'focus', function() {
            document.designMode = 'on';
        });
        addEvent(editableReadOnly, 'focus', function() {
            document.designMode = 'on';
        });

        if (localStorage.getItem('Tester')) {
            editableTester.innerHTML = localStorage.getItem('Tester');
        }
        if (localStorage.getItem('Subscriber')) {
            editableSubscriber.innerHTML = localStorage.getItem('Subscriber');
        }
        if (localStorage.getItem('ReadOnly')) {
            editableReadOnly.innerHTML = localStorage.getItem('ReadOnly');
        }               
    </script>

问题是:

我总能编辑div 但有时localStorage在编辑后不会使用我的div的新值更新。 重新加载窗口后,所有值都是旧值。但它很奇怪:有时它可以工作,如果我在新窗口中打开代码。有任何想法吗? (对不起我的英文)

1 个答案:

答案 0 :(得分:0)

在DOM完全加载后运行脚本吗?许多方法来实现这一目标。但最简单的可能是使用jQuery (document).ready(//here comes your code)