localStorage未定义
有了这个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)"/>
我得到undefinedundefinedundefined...
在控制台上。
我错过了什么?
您需要传递textarea的值,并将存储密钥传递给appendToStorage
。
因此,最好使用另一种方法,只需点击按钮即可进行呼叫
<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
}
演示:小提琴
很难告诉你要在这里实现什么,但最简单的解决方案是让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/36275.html