localStorage undefined
with this function
:
function appendToStorage(name, data) {
var old = localStorage.getItem(name);
if (old === null) old = '';
localStorage.setItem(name, old + data);
}
appendToStorage('oldData', $('textbox').value);
and this html
:
<textarea name ="textbox" cols="50" rows="5">
say it...
</textarea><br>
<input type="submit" onclick="appendToStorage(name, data)"/>
I get undefinedundefinedundefined...
on the console.
what I am missing?
You need to pass the textarea's value, and the storage key to appendToStorage
.
So it is better to use a another method which does that an call that on click of the button like
<input type="submit" onclick="addTextArea();" />
then
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
}
Demo: Fiddle
很难告诉你要在这里实现什么,但最简单的解决方案是让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>
链接地址: http://www.djcxy.com/p/36276.html
上一篇: 使用jquery通过数组索引和名称属性设置文本框值
下一篇: localStorage未定义