localStorage与Javascript函数冲突

时间:2016-04-06 07:34:06

标签: javascript jquery html html5

我正在使用localStorage在以下内容刷新浏览器后保存以HTML格式填写的值:

<form id="localStorageTest" method="post" action="">
            <label>Name:</label>
            <input type="text" name="name" id="name" class="stored" value="" />

            <label>Email:</label>
            <input type="email" name="email" id="email" class="stored" value="" />

            <label>Message:</label>
            <textarea name="message" id="message" class="stored"></textarea>

            <input type="submit" class="demo-button" value="Submit" />
        </form>

<script type="text/javascript">
$(document).ready(function () {
    function init() {
        if (localStorage["name"]) {
            $('#name').val(localStorage["name"]);
        }
        if (localStorage["email"]) {
            $('#email').val(localStorage["email"]);
        }
        if (localStorage["message"]) {
            $('#message').val(localStorage["message"]);
        }
    }
    init();
});

$('.stored').change(function () {
    localStorage[$(this).attr('name')] = $(this).val();
});

$('#localStorageTest').submit(function() {
    localStorage.clear();
});
</script>

以上单独的代码正常工作,但是如果我在<head></head>部分使用Javascript函数它会停止填充值。

这是我发现冲突的Javascript函数,如果我删除它,localStorage正常工作。

$(function() {
    $("[type=date]").datepicker({
        monthNamesShort: $.datepicker.regional["en"].monthNames,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        yearRange: "-116:+10"
    });
});
$.fn.optionTest = function(opts) {
    var option = $.extend({}, $.fn.optionTest.defaults, opts);
    $(this).change(function() {
        option.holderObject = $(this);
        if (option.clearOnChange) {
            $(option.actionId).empty();
        }
        var val = $(this).val();
        if ($.fn.optionTest.isArray(val)) {
            $.fn.optionTest.parseArray(val, option);
        } else {
            var label = $(this).children("option:selected").eq(0).text();
            $.fn.optionTest.parseContent(val, option, label);
        }
        $('.' + option.removeLinkOptions.class).click(function(event) {
            $.fn.optionTest.removeRow(this, option);
            event.preventDefault();
        });

        $("[type=date]").datepicker({
            monthNamesShort: $.datepicker.regional["en"].monthNames,
            changeMonth: true,
            changeYear: true,
            dateFormat: 'yy-mm-dd',
            yearRange: "-116:+10",
        });
        return this;
    });
};

我发现奇怪的事情,即使我只是离开:

$.fn.optionTest = function(opts) {

};

或仅此(不含$.fn.optionTest):

$(function() {
    $("[type=date]").datepicker({
        monthNamesShort: $.datepicker.regional["en"].monthNames,
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',
        yearRange: "-116:+10"
    });
});

localStorage仍未填写数据。为什么会这样?我怎么解决呢?

更新

我改变了它,但仍然是相同的:

<script type="text/javascript">
$(document).ready(function () {
    function init() {
        if (localStorage["name"]) {
            $('#name').val(localStorage["name"]);
        }
        if (localStorage["email"]) {
            $('#email').val(localStorage["email"]);
        }
        if (localStorage["message"]) {
            $('#message').val(localStorage["message"]);
        }
    }
    init();

    $('.stored').change(function () {
        localStorage[$(this).attr('name')] = $(this).val();
    });

    $('#localStorageTest').submit(function() {
        localStorage.clear();
    });
});
</script>

我在HTML表单下使用此代码。

如前所述,如果我从<head></head>移除以下功能,它就会开始工作......

$.fn.optionTest = function(opts) {
   .....
}; 

4 个答案:

答案 0 :(得分:0)

如果将工作脚本放在头部,则需要在$(document).ready(function(){})中移动.change和.submit函数,以便在绑定之前存在元素。事件处理程序。

答案 1 :(得分:0)

小提琴:http://jsfiddle.net/r6gk8L86/15/

&#13;
&#13;
setTimeout( load_all, 1000 ); // Delayed run so you can see it loads

/** Load stored values for all inputs */
function load_all () {
   try { // Check browser support
      localStorage.length;
      $( '.stored' ).each( load_one ).on( 'input', save );
   } catch ( err ) {
      $("#localStorageTest").prepend( '<p>Sorry, no Web Storage: "'+err+'"</p>' );
   }
}

/** Load stored value for an input */
function load_one () {
   this.value = localStorage.getItem( this.id ) || '';
}

/** Save value to store */
function save ( event ) {
   var element = event.target;
   if ( element.value )
      localStorage.setItem( element.id, element.value );
   else
      localStorage.removeItem( element.id );
}
&#13;
label { font-family: monospace; }
&#13;
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<form id="localStorageTest" method="post" action="">
   This won't run on StackOverflow because its snippet is sandboxed. (no storage access)<br/>
   <!-- 20 text fields + 20 email fields + 1 textarea -->
   <label>Name :</label> <input name= "name00" id= "name00" class="stored" placeholder= "name00" />
   <label>Email:</label> <input name="email00" id="email00" class="stored" placeholder="email00" type="email" /><br/>
   <label>Name :</label> <input name= "name01" id= "name01" class="stored" placeholder= "name01" />
   <label>Email:</label> <input name="email01" id="email01" class="stored" placeholder="email01" type="email" /><br/>
   <label>Name :</label> <input name= "name02" id= "name02" class="stored" placeholder= "name02" />
   <label>Email:</label> <input name="email02" id="email02" class="stored" placeholder="email02" type="email" /><br/>
   <label>Name :</label> <input name= "name03" id= "name03" class="stored" placeholder= "name03" />
   <label>Email:</label> <input name="email03" id="email03" class="stored" placeholder="email03" type="email" /><br/>
   <label>Name :</label> <input name= "name04" id= "name04" class="stored" placeholder= "name04" />
   <label>Email:</label> <input name="email04" id="email04" class="stored" placeholder="email04" type="email" /><br/>
   <label>Name :</label> <input name= "name05" id= "name05" class="stored" placeholder= "name05" />
   <label>Email:</label> <input name="email05" id="email05" class="stored" placeholder="email05" type="email" /><br/>
   <label>Name :</label> <input name= "name06" id= "name06" class="stored" placeholder= "name06" />
   <label>Email:</label> <input name="email06" id="email06" class="stored" placeholder="email06" type="email" /><br/>
   <label>Name :</label> <input name= "name07" id= "name07" class="stored" placeholder= "name07" />
   <label>Email:</label> <input name="email07" id="email07" class="stored" placeholder="email07" type="email" /><br/>
   <label>Name :</label> <input name= "name08" id= "name08" class="stored" placeholder= "name08" />
   <label>Email:</label> <input name="email08" id="email08" class="stored" placeholder="email08" type="email" /><br/>
   <label>Name :</label> <input name= "name09" id= "name09" class="stored" placeholder= "name09" />
   <label>Email:</label> <input name="email09" id="email09" class="stored" placeholder="email09" type="email" /><br/>
   <label>Name :</label> <input name= "name10" id= "name10" class="stored" placeholder= "name10" />
   <label>Email:</label> <input name="email10" id="email10" class="stored" placeholder="email10" type="email" /><br/>
   <label>Name :</label> <input name= "name11" id= "name11" class="stored" placeholder= "name11" />
   <label>Email:</label> <input name="email11" id="email11" class="stored" placeholder="email11" type="email" /><br/>
   <label>Name :</label> <input name= "name12" id= "name12" class="stored" placeholder= "name12" />
   <label>Email:</label> <input name="email12" id="email12" class="stored" placeholder="email12" type="email" /><br/>
   <label>Name :</label> <input name= "name13" id= "name13" class="stored" placeholder= "name13" />
   <label>Email:</label> <input name="email13" id="email13" class="stored" placeholder="email13" type="email" /><br/>
   <label>Name :</label> <input name= "name14" id= "name14" class="stored" placeholder= "name14" />
   <label>Email:</label> <input name="email14" id="email14" class="stored" placeholder="email14" type="email" /><br/>
   <label>Name :</label> <input name= "name15" id= "name15" class="stored" placeholder= "name15" />
   <label>Email:</label> <input name="email15" id="email15" class="stored" placeholder="email15" type="email" /><br/>
   <label>Name :</label> <input name= "name16" id= "name16" class="stored" placeholder= "name16" />
   <label>Email:</label> <input name="email16" id="email16" class="stored" placeholder="email16" type="email" /><br/>
   <label>Name :</label> <input name= "name17" id= "name17" class="stored" placeholder= "name17" />
   <label>Email:</label> <input name="email17" id="email17" class="stored" placeholder="email17" type="email" /><br/>
   <label>Name :</label> <input name= "name18" id= "name18" class="stored" placeholder= "name18" />
   <label>Email:</label> <input name="email18" id="email18" class="stored" placeholder="email18" type="email" /><br/>
   <label>Name    :</label> <input name= "name19" id= "name19" class="stored" placeholder= "name19" />
   <label>Email:</label> <input name="email19" id="email19" class="stored" placeholder="email19" type="email" /><br/>

   <label>Message:</label>
   <textarea name="message" id="message" class="stored" placeholder="message"></textarea>

   <input type="submit" class="demo-button" value="Submit" />
</form>
&#13;
&#13;
&#13;

  

怎么玩:打开小提琴,输入一些文字,然后重新运行。首次加载时,输入为空。一秒钟之后,他们将加载您之前输入的内容。

您的存储应用程序似乎存在问题,而不是特定问题。

上面是一个工作小提琴。以下是它的工作原理:

  1. 代码有40个输入字段,每个字段都有唯一的ID。
    (使用不同的id来区分不同形式的相同名称字段)

  2. 在页面加载时,运行使用try catch检测load_all的{​​{1}}。
    如果没问题,它会为每个输入字段调用localStorage,然后将函数load_one挂钩到它们的save事件。
    (try catch可以检测input存在但访问被拒绝的情况,例如SO片段。)

  3. Storage会将load_one当前输入(id)作为关键字,并从this加载值。
    (此处的代码默认为空。如果没有值,更好的代码应跳过设置。)

  4. 更改输入后,localStorage会将当前输入的saveid)作为键,并保存其值(如果非空)或从event.target删除其条目(如果为空)。
    (存储空间有限。清理它的好习惯。)

答案 2 :(得分:0)

我个人认为您在页面的head部分有一些错误,因此javascript的其余部分(您在LocalStorage中存储数据的部分)不会运行。正如user1273587指出的那样,您是否查看了开发人员控制台以查看是否存在任何错误?

答案 3 :(得分:0)

相当多的逻辑歧义只能提供可能性:

  1. localStorage.clear();更好地使用.removeItem(“...”)
  2. localStorage.setItem(“”)在哪里?我可以阅读$(。stored)
  3. 但是怎么做

    localStorage [$(this).attr('name')] = $(this).val();

    为你工作?

    希望我能提供更好的答案,如果我提到的内容与你纠正和回应有关。