localStorage undefined

时间:2015-07-07 04:41:28

标签: javascript html5 local-storage

使用此/*Variable A; /** javadocs *//* Variable B;*/

function

function appendToStorage(name, data) { var old = localStorage.getItem(name); if (old === null) old = ''; localStorage.setItem(name, old + data); } appendToStorage('oldData', $('textbox').value);

html

我在控制台上获得<textarea name ="textbox" cols="50" rows="5"> say it... </textarea><br> <input type="submit" onclick="appendToStorage(name, data)"/>

我缺少什么?

2 个答案:

答案 0 :(得分:2)

您需要将textarea的值和存储密钥传递给<input type="submit" onclick="addTextArea();" />

因此,最好使用另一种方法,即点击按钮(例如

)进行调用
function appendToStorage(name, data) {
    var old = localStorage.getItem(name);
    if (old === null) old = '';
    localStorage.setItem(name, old + data);
}
addTextArea();

function addTextArea() {
    appendToStorage('oldData', $('textarea[name="textbox"]').val());//use .val() to get the value, also need to use attribute selecotr for name
}

然后

{{1}}

演示:Fiddle

答案 1 :(得分:1)

很难说出你想要在这里实现什么,但最简单的解决方案是让你的appendToStorage功能完成工作:

function appendToStorage (name) {
  
  // get the target element by it's name
  var el = document.querySelector('[name="' + name + '"]');
  
  // check we're getting the correct info
  console.log("[" + name + "]:", el.value);
  
  // save it to storage (you may also want to retrieve the last value and append it)
  window.localStorage.setItem(name, el.value);
}
input {display: block; margin: 0 0 1em; } pre { font-size: 0.9em; display: block; margin: 0.5em 0; }
<script>console.log = function () { document.getElementById("output").innerHTML = Array.prototype.slice.call(arguments).join(" "); }</script>
<textarea name="textbox" cols="50" rows="3">
say it...
</textarea>
<input type="submit" onclick="appendToStorage('textbox')"/>
<textarea name="textbox-again" cols="50" rows="3">
say it again...
</textarea><br>
<input type="submit" onclick="appendToStorage('textbox-again')"/>
<pre id="output"></pre>

注意:上述内容并未反映最佳做法,但它确实显示了如何从文本字段中检索值。