2015-07-07 3 views
1

с этим function:LocalStorage неопределенными

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... на консоли.

что мне не хватает?

+2

Откуда вы получаете переменные 'name' и' data', из обработчика 'onclick'? –

+0

Попробуйте отладить его с помощью точек останова. Определенно некоторое значение не определено. – AkshayJ

ответ

2

Вам необходимо передать значение 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 
} 

Демо: Fiddle

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>

Примечание: выше, не отражают наилучшую практику, однако он показывает, как получить значение из вашего текстового поля.

Смежные вопросы