通过JS自动提交表单(Timeout,TimeInterval)

时间:2017-05-01 17:49:10

标签: javascript jquery forms input timeout

我想创建简单的自动提交。例如,如果用户1秒没有在输入中键入任何内容或按下输入它提交。我的代码:



$(document).on('keypress', $('input'), function(e) {
  console.log('clear')
  
  clearInterval(SubmitInterval);
  
  if (e.which == 13) {
    console.log('submit')
  }
  
  var SubmitInterval = setInterval(function() {
    console.log('submit')
    clearInterval(SubmitInterval);
  }, 1000);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=1 />
&#13;
&#13;
&#13;

但它的工作很糟糕。 感谢

2 个答案:

答案 0 :(得分:0)

问题是由于您在每个按键上重新定义SubmitInterval变量。而是在事件处理程序之外声明一次。试试这个:

&#13;
&#13;
var submitInterval;

$(document).on('keypress', 'input', function(e) {
  console.log('clear')
  
  clearInterval(submitInterval);
  
  if (e.which == 13) {
    console.log('submit')
  }
  
  submitInterval = setInterval(function() {
    console.log('submit')
    clearInterval(submitInterval);
  }, 1000);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=1 />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

现在一切正常。感谢。

var SubmitInterval;
$(document).on('keypress', $('input'), function(e) {
  clearInterval(SubmitInterval);
  SubmitInterval = setInterval(function () {
    console.log('submit');
    clearInterval(SubmitInterval);
  },1700);
  if(e.which == 13) {
	  console.log('submit');
	  clearInterval(SubmitInterval);
	};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text />