简体   繁体   English

如何摆脱JavaScript中的表单输入值缓存​​?

[英]How do I get rid of form input value cache in JavaScript?

This is my code in JavaScript: 这是我在JavaScript中的代码:

function myfunction() {
    var increment = $("#increment").val();
    $("#increment").val(parseInt($("#increment").val()) + 1);
}

and HTML: 和HTML:

<input id="increment" value="0" type="hidden">

The idea is when I click on my button the myfunction is called and increment my input type hidden with one. 这个想法是,当我单击我的按钮时,将调用myfunction并增加隐藏的输入类型。 It works. 有用。 If press the F5 button the value from the input type hidden remain with the last increment number. 如果按F5键,则隐藏的输入类型的值将保留最后一个增量编号。

If I press Ctrl + F5 the value from my input will be set to 0 . 如果按Ctrl + F5,则输入的值将设置为0 Why? 为什么? How do I build my code in order to set my input to 0 when I simply refresh my page with F5 ? 当我仅用F5刷新页面时,如何构建代码以将输入设置为0

You could simply set the value to 0 on page load: 您可以将页面加载时的值简单地设置为0:

$(function() {
    $("#increment").val('0');
});

EDIT: Samuels answer above solves this specific issue brilliantly, that is, by resetting back to 0. My answer below is the generic way to prevent browsers from persisting FORM data when you refresh. 编辑:上面的塞缪尔(Samuels)答案很好地解决了这个特定问题,也就是将其重置为0。下面的答案是防止浏览器在刷新时保留FORM数据的通用方法。 To do that, the browser cache needs to be disabled. 为此,需要禁用浏览器缓存。

You need to disable client caching in the browser. 您需要在浏览器中禁用客户端缓存。

The only way to do that on the client side is by using meta tags: 在客户端执行此操作的唯一方法是使用元标记:

<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />

Just before the function do the following: 在该函数之前,请执行以下操作:

$('#increment').val(''); // This should always make the input clear of any value when the page loads
function myfunction(){
    var increment = $("#increment").val();
    $("#increment").val(parseInt($("#increment").val()) + 1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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