如何保持测试数据的完整性?

时间:2017-09-18 03:05:37

标签: javascript jquery

如何阻止表单刷新我希望能够成功发送表单的页面,并且仍然保持黄金输入值不变。首次按下经过验证的按钮时会创建该值。

换句话说,我不希望页面刷新,但我仍然希望它能够成功提交表单。我创建了一个测试按钮调用,证明在您提交表单后是否刷新页面。

这是代码



*, *:before, *:after {
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

body {
  font-family: 'Nunito', sans-serif;
  color: black;
}

#myField {
background: gold;  
}

form {
  max-width: 200px;
  margin: 10px auto;
  padding: 10px 20px;
  background: red;
  border-radius: 8px;
}

h1 {
  margin: 0 0 30px 0;
  text-align: center;
  color: white;
}


#x {
  background: rgba(255,255,255,0.1);
  border: none;
  font-size: 16px;
  height: auto;
  margin: 0;
  outline: 0;
  padding: 15px;
  width: 100%;
  background-color: white;
  color: black;
  box-shadow: 0 1px 0 rgba(0,0,0,0.03) inset;
  margin-bottom: 30px;
}

input[type="radio"],
input[type="checkbox"] {
  margin: 0 4px 8px 0;
}

select {
  padding: 6px;
  height: 32px;
  border-radius: 2px;
}

button {
  padding: 19px 39px 18px 39px;
  color: white;
  background-color: blue;
  font-size: 18px;
  text-align: center;
  font-style: normal;
  border-radius: 5px;
  width: 100%;
  border: 1px solid blue;
  border-width: 1px 1px 3px;
  box-shadow: 0 -1px 0 rgba(255,255,255,0.1) inset;
  margin-bottom: 10px;
}

fieldset {
  margin-bottom: 30px;
  border: none;
}

legend {
  font-size: 1.4em;
  margin-bottom: 10px;
}

label {
  display: block;
  margin-bottom: 8px;
  color: white;
}

label.light {
  font-weight: 300;
  display: inline;
}

.number {
  background-color: #5fcf80;
  color: #fff;
  height: 30px;
  width: 30px;
  display: inline-block;
  font-size: 0.8em;
  margin-right: 4px;
  line-height: 30px;
  text-align: center;
  text-shadow: 0 1px 0 rgba(255,255,255,0.2);
  border-radius: 100%;
}

@media screen and (min-width: 480px) {

  form {
    max-width: 480px;
  }

}

<script>
var i=0;
function increase()
{
	i++;
var x=( ' '+   (i));  
  document.getElementById('myField').value = x;
 //..
}
</script>
<p style="width: 350px;">Press the proven button first and then fill in the name input and press the submit button. If the number disappers in the proven input then that proves that the form can still refresh the page.</p>
<input type="button" Value="Proven"  onclick="increase();">
<input type="text" id="myField" value="" />
<br>
<br>
<br>
<form action="" method="post">
  <h1>Form</h1>
  <label for="x">NAME</label>
  <input type="text" id="x">
  <button type="submit">SUBMIT</button> 
</form>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

刷新页面时,HTML数据通常会丢失。您可以通过多种方式保留数据,但必须手动实施更多详细信息

最简单和最广泛支持的是WebStorage,其中您拥有持久存储(localStorage)或基于会话(sessionStorage),它在内存中,直到您关闭浏览器。

我认为你现在正在寻找localStorage

window.onbeforeunload = function() {
    localStorage.setItem(myField, $('#myField').val());

    // ...
}

加载页面时:

window.onload = function() {

    var name = localStorage.getItem(myField);
    if (myField!== null) $('#myField').val(myField);

    // ...
}