3

当我单击保存按钮时,我正在使用jStorage来存储输入的值。然后我想将存储的值设置为页面加载时的当前输入值。虽然它工作得不太好。

HTML

<input type='text' id='name'>
<div id="save">Save</div>

JS

$('#save').click(function() {
  $.jStorage.set("key", $("#name").val());
});

var input_value = $.jStorage.get("key");
4

1 回答 1

4

It's a little tangled up:

$.jStorage.set("key", $("#name").val());

var input_value = $.jStorage.get("key");

When you're passing a selector to jQuery you have to pass a valid string, not just the raw CSS selector syntax. That is, you've got to get the selector expression into JavaScript first, and you do that by creating a string constant.

edit — If you want your <input> to show the last-saved value when the page loads, you'd do something like this:

$(function() {
  $('#name').val( $.jStorage.get("key") || "" );
});

Wrapping the activity in a $(function() { ... }) wrapper ensures that the code won't run until the <input> field has been seen and parsed by the browser, but still very soon after the user sees the page load (essentially immediately).

Adding the extra || "" bit after the jStorage call ensures that if the value is null or undefined the user won't see that. If there's no stored value, in other words, that'll have the input just be empty. You could put any other default value in there of course.

于 2013-11-30T23:09:22.010 回答