我正在尝试提交表单,并且在提交时我调用了myOwnFun
这个函数,它可以运行。但是,如果我长时间按Enter键,则表单提交会重复,这是我不希望的。
这是代码。
<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键运行此功能。而且我需要多次提交表单。
答案 0 :(得分:2)
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>
答案 1 :(得分:1)
先在脚本中然后在代码中使用e.preventDefault()
方法,这将禁用表单的默认功能并执行代码。
答案 2 :(得分:1)
尝试一下:
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() {
var executed = false;
return function() {
if (!executed) {
executed = true;
console.log('show text one time in one Enter')
}
};
}
答案 3 :(得分:1)
您可以使用:form.removeEventListener("submit", yourFunction);
我认为您必须将function(e)
更改为“真实函数”以使其起作用
答案 4 :(得分:1)
作为“向其扔库/程序包”解决方案,Lodash具有once
函数,该函数将函数限制为每个页面加载一次调用:https://lodash.com/docs/4.17.11#once。可能有些矫kill过正,尤其是如果您只需要一行的话,因此即使您使用独立软件包,我也建议将其作为最后的选择。