简体   繁体   中英

Can you use jquery in sessionStorage?

I have code like this:

$(document).ready(function() {

var field = $('#field').val();

if (sessionStorage.getItem('save')) {
    $('#field').val(sessionStorage.getItem('save'));
}

field.addEventListener("change", function() {
    sessionStorage.setItem('save', field);
});

});

<input id="field" type="text"></input>

http://jsfiddle.net/oae8krpm/

But it doesn't seem to work with jQuery, can it?

Thanks

field.addEventListener

field is the text value of the field, not the DOM object for the field. Use $('#field').get(0).addEventListener , or just jQuery event handling ( on et al).

sessionStorage.setItem('save', field);

field is the text value of the field at the point you read it on document-ready. If you want to store the new value it was changed to, you'll need to read it again:

$('#field').on('change', function() {
    sessionStorage.setItem('save', $('#field').val());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM