我想创建简单的自动提交。例如,如果用户1秒不要在输入中输入任何内容或按Enter键提交。我的代码:
$(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 />
但效果不佳。谢谢
问题是由于您重新定义了每个按键上的SubmitInterval
变量。而是在活动处理程序之外声明一次。尝试以下操作:
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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id=1 />
现在一切都很好。谢谢。
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 />