我正在开发一个小型网站,无法在网页上保持成本值的持久性。
我尝试过使用 Html5 存储,但无法让它工作。
这是我的 JavaScript:
function modifyPrice(cost) {
// body...
var total = document.getElementById('totalCost');
var accumulte = total.value;
var temp = cost + Number.isInteger(accumulte) + 15;
total.value = temp;
localStorage.setItem("priceTag",temp);
document.getElementById('pricetag').innerHTML = localStorage.getItem("priceTag");
}
这是我的示例 html:
<span>
<span name="price" id="pricetag"></span> $
</span>
这可能是我执行localStorage的方式还是有更好的方法?
最佳答案
Number.isInteger(accumulte)
返回 bool 结果。所以你必须将代码更改为类似
var calculate = document.getElementById('calculate');
calculate.addEventListener("click", function() {
var total = document.getElementById('totalCost'),
accumulte = +total.value, // casting int to string.
cost = 10,
temp = cost + (Number.isInteger(accumulte) ? parseInt(accumulte, 10) : 0) + 15;
alert("Value when accumulte is " + total.value + " = " + temp);
}, false);
<input type="text" value="07" id="totalCost" />
<input type="button" value="Calculate" id="calculate" />
关于javascript - 使用 HTML5 本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41583782/