问题描述
我的代码完美地改变了页面加载时自动输入的值,并且它之间有延迟。
My code worked perfectly on changed the value of input automatic on page load with a delay between it.
但是还有另外一个问题,当我试图模拟按输入上的 [enter]
键时,它不是工作,它提交表单,然后重新加载我的页面。
But there's another problem, When I tried to simulate pressing the [enter]
key on the input, it's no working, and it's submit the form and reload my page instead.
我如何模拟在输入中按 [enter]
键而不提交表格而不重新加载我的页面?我使用纯 javascript
没有 jQuery
How I simulate pressing the [enter]
key in the input without submit the form and without reload my page? I am use pure javascript
without jQuery
这是我的脚本:
var form = document.querySelectorAll("._k3t69");
var input = document.querySelectorAll("._7uiwk._qy55y");
var message = "Replacement..." ;
var maxMsg = 3 ;
var delay = 2.5 * 1000 ; // 2.5 Seconds
var j = 0, k = 0;
function setValue(){
if( j == maxMsg || j == input.length) {
clearInterval(looping)
} else {
input[j++].value = message ;
//And then simulate pressing enter key ON THE INPUT, not sumbit the form
form[k++].submit();
}
}
var looping = setInterval(setValue, delay);
<form class="_k3t69">
<input type="text" class="_7uiwk _qy55y">
</form>
<form class="_k3t69">
<input type="text" class="_7uiwk _qy55y">
</form>
<form class="_k3t69">
<input type="text" class="_7uiwk _qy55y">
</form>
Here's the fiddle
推荐答案
默认提交表格将提交表格并重新加载页面。
Submitting the form by default will submit the form and reload the page.
如果你想触发按键事件:
If you want to trigger keypress event:
var input = document.querySelector("._7uiwk._qy55y");
var ev = document.createEvent('Event');
ev.initEvent('keypress');
ev.which = ev.keyCode = 13;
input.dispatchEvent(ev);
如果你想检查是否输入了按键:
If you want to check if pressed key is enter:
var input = document.querySelector("._7uiwk._qy55y");
input.addEventListener('keypress', function(ev){
if(ev.keyCode === 13 || ev.which === 13){
// enter was pressed
}
});
如果您想阻止在输入/提交时提交表单:
If you want to prevent submitting the form on enter/submit:
var form = document.querySelector("._k3t69");
form.addEventListener('submit', function(ev){
ev.preventDefault();
// you can do something alternative here e.g. send AJAX request to server
return false;
});
JSFIDDLE
这篇关于模拟在输入文本上按[enter]键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!