gpt4 book ai didi

javascript - 提交时只调用一次函数

转载 作者:太空宇宙 更新时间:2023-11-04 14:25:44 25 4
gpt4 key购买 nike

我正在尝试提交一个表单,在提交时我调用了一个 myOwnFun 函数,它运行了。但是如果我长时间按回车键,表单提交会重复我不想要的。

这是代码..

<form class="user__answer-form">
<input type="text" name="useranswer" class="user__answer">
</form>
const form = document.querySelector('.user__answer-form');
const formAnswer = document.querySelector('.user__answer');

formAnswer.focus();

form.addEventListener('submit', function(e) {
e.preventDefault();
myOwnFun();
});


function myOwnFun() {
console.log('show text one time in one Enter')
}

我只想在按下 enter 时运行此功能一次,即使我按下的时间更长。而且我需要多次提交表单。

最佳答案

const form = document.querySelector('.user__answer-form');
const formAnswer = document.querySelector('.user__answer');

//create a counter to track key down events
let count = 0;

formAnswer.focus();

form.addEventListener('submit', function(e) {
e.preventDefault();
//call your function only if count is 0
//ie is first time enter key is pressed

//if key is pressed for a long time count > 0
// this condition fails
if(count == 1){
myOwnFun();
}

});

//fires on any key is pressed on form element
form.addEventListener('keydown', function(e) {
// for cross browser compatibility
const keyCode = e.which || e.keyCode;

if(keyCode == 13){
//if enter key is pressed update count
count ++;
}
});

//fires on key is released on form element
form.addEventListener('keyup', function(e) {

const keyCode = e.which || e.keyCode;
//if enter key is released reset the count
if(keyCode == 13){
count = 0
}

});



function myOwnFun() {
console.log('show text one time in one Enter');
}
<form class="user__answer-form" >
<input type="text" name="useranswer" class="user__answer">
</form>

关于javascript - 提交时只调用一次函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55723920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com