我尝试从上次访问输入的输入值中获取所有localStorage
个存储数据。
到目前为止,我能够存储&显示input
的1& 2但不是这两者之间的减法结果。
我想存储并显示页面加载/刷新上次访问减法结果。
最后你重新加载小提琴,只看到最后输入的input
值,而不是减法结果(也是所希望的):
|=========> External JSFiddle (not working if I embed it) <=========|
HTML:
<form action="">
<input type="text" id="input1" value="0" name="input1">
<input type="text" id="input2" value="0" name="input2">
</form>
<span id="total"></span>
jQuery的:
$(document).ready(function() {
getLocalStorage();
});
$("form").keyup(function() {
var input1 = parseFloat($("#input1").val());
var input2 = parseFloat($("#input2").val());
var total = input2 - input1;
$("#total").text(total);
});
function getLocalStorage() {
if (localStorage["input1"]) {
$('#input1').val(localStorage["input1"]);
}
if (localStorage["input2"]) {
$('#input2').val(localStorage["input2"]);
}
if (localStorage[$("#total")]) {
$('#total').html(localStorage[$("#total")]);
}
};
$('input').keyup(function() {
localStorage[$(this).attr('name')] = $(this).val();
localStorage[$("#total")] = $(this).html();
});
我没有运气地检查了几个问题:
答案 0 :(得分:1)
你正在保存总错误。检查此工作fiddle。
以下是修改后的代码:
$(document).ready(function() {
getLocalStorage();
});
$("form").keyup(function() {
var input1 = parseFloat($("#input1").val());
var input2 = parseFloat($("#input2").val());
var total = input2 - input1;
$("#total").text(total);
});
function getLocalStorage() {
if (localStorage["input1"]) {
$('#input1').val(localStorage["input1"]);
}
if (localStorage["input2"]) {
$('#input2').val(localStorage["input2"]);
}
if (localStorage["total"]) {
$('#total').html(localStorage["total"]);
}
};
$('input').keyup(function() {
localStorage[$(this).attr('name')] = $(this).val();
localStorage["total"] = $('#total').html();
});
答案 1 :(得分:0)
您需要将localStorage
存储和检索为字符串,而不是$('#total')
的jquery对象。我更新了您的代码以设置localStorage['total']
而不是localStorage[$('#total')]
。我还整合了$("form").keyup()
和$("input").keyup()
事件处理程序,因为看起来您只需要$("input").keyup()
。
https://jsfiddle.net/a7bs8jh1/3/
$(document).ready(function() {
getLocalStorage();
});
function getLocalStorage() {
if (localStorage["input1"]) {
$('#input1').val(localStorage["input1"]);
}
if (localStorage["input2"]) {
$('#input2').val(localStorage["input2"]);
}
if (localStorage['total']) {
$('#total').html(localStorage['total']);
}
};
$('input').keyup(function() {
var input1 = parseFloat($("#input1").val());
var input2 = parseFloat($("#input2").val());
var total = input2 - input1;
localStorage[$(this).attr('name')] = $(this).val();
localStorage['total'] = total;
$("#total").text(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="">
<input type="text" id="input1" value="0" name="input1">
<input type="text" id="input2" value="0" name="input2">
</form>
<span id="total"></span>