I'm using pure html5 sliders as such:
<div>Brush Size:<input id="brush_size" type="range" value="10" min="1" max="100"/></div>
<div>Opacity: <input id="opacity" type="range" value="0.8" step="0.01" min="0.01" max="1.00"/></div>
Then saving the values into localStorage onChange:
$("#brush_size").change(function(){
localStorage['brush_size']=this.value;
});
$("#opacity").change(function(){
localStorage['opacity']=this.value;
});
After changes, on the next page load I wou开发者_运维技巧ld like to see the current localStorage values, instead of the html hardcoded values. What's the best way of doing this?
I suppose I could set the slider's value to the localStorage values during page load using jQuery... is this the best-practices way of doing it?
Just add this to your code
$("#brush_size").val(localStorage['brush_size']);
$("#opacity").val(localStorage['opacity']);
This should suffice:
$(function ()
{
var ids = ['brush_size', 'opacity' /* etc */],
id,
value;
for (var i=0; i<ids.length; i++)
{
id = ids[i];
value = localStorage[id];
if (typeof value !== 'undefined')
{
$('#'+id).val(value);
}
}
});
Side note: you should probably be using $(this).val()
instead of this.value
in the change
callbacks, and you can make that code more concise overall:
$('#brush_size, #opacity').change(function ()
{
localStorage[this.id] = $(this).val();
});
Demo: http://jsfiddle.net/mattball/G59QH/ (courtesy of @David)
精彩评论