Javascript,而不是保存到localstorage

时间:2017-09-06 12:09:59

标签: javascript jquery

我遇到了一个小问题,我试图保存输入字段的值" a1"进入本地存储,但由于某种原因,它没有保存。我似乎无法弄清问题是什么......

感谢所有帮助!

已修复:将脚本放在底部。

    <!DOCTYPE html>
<html>
<head>
    <script src="jquery.js"></script>
    <script>
        document.getElementById('a1').onkeyup = function() {
            var a1 = document.getElementById('a1').value;
            localStorage.setItem('a1', a1);
        };
    </script>
    <link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>

<div class="box">
    <div class="title">Kalkulator</div>
    <div class="text">Antal kvadratmeter: <input class="input-field" id="a1" type="text" value="0" /> m2</div> <---- HERE
    <div class="text">Kantklipp rundt plenen? (+3.00kr per m): <input class="input-field" id="a2" type="text" value="0" /> m</div>
    <div class="text">Gjødsel? (+1.00kr per kvm) <input class="input-field2" type="checkbox" name="checkbox" id="checkbox_check2"></div>
    <div class="text">Mosefjerning? (+2.00kr per kvm) <input class="input-field2" type="checkbox" name="checkbox" id="checkbox_check3"></div>
    <div class="text">Pris (kr) <input class="input-field3" id="a4" type="text" value="0.00" /></div>
    <div class="text2">Obs! Minstepris på 300kr.</div>
    <div class="tilbud-knapp">Legg til i tilbuds liste</div>
    <div class="border"></div>
</div>

1 个答案:

答案 0 :(得分:3)

将代码放在页面底部。它在呈现元素之前运行,这意味着事件无法注册到元素。

断裂:

&#13;
&#13;
<script>
    document.getElementById('a1').onkeyup = function() {
        var a1 = document.getElementById('a1').value;
        localStorage.setItem('a1', a1);
    };
</script>
<input class="input-field" id="a1" type="text" value="0" /> 
&#13;
&#13;
&#13;

已修复(localStorage个可用于片段中除外):

&#13;
&#13;
<input class="input-field" id="a1" type="text" value="0" /> 
<script>
    document.getElementById('a1').onkeyup = function() {
        var a1 = document.getElementById('a1').value;
        localStorage.setItem('a1', a1);
    };
</script>
&#13;
&#13;
&#13;