[英]Javascript | Enter key first time should press a button, second time should press a label or url
First time we press keyboard enter key should execute button(id="botonCorregir").我们第一次按键盘回车键应该执行 button(id="botonCorregir")。 But the second time we press enter key should execute url().但是我们第二次按回车键应该执行 url()。 I use cont, for the first time execute one part of the javascript code, and after when de cont value is 1, execute the second part of javascript code.我用cont,第一次执行javascript代码的一部分,当de cont值为1后,执行javascript代码的第二部分。 For some mistake, it doesn´t work.对于一些错误,它不起作用。
thanks!谢谢!
HTML: HTML:
<input id="respuestaUsuario"></input>
<button id="botonCorregir">Reply</button>
<a id="enlaceSiguiente" href="nextQuestion.html">Next question</a>
JAVASCRIPT: JAVASCRIPT:
<script>
var cont=0;
if(cont==0){
//Should enter the first press of enter
var input = document.getElementById("respuestaUsuario");
console.log('input: ', input)
input.addEventListener("keyup", function(event) {
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("botonCorregir").click();
}
});
cont++;
}else{
//Should enter the second press of enter
if (event.keyCode == 13) {
event.preventDefault();
document.getElementById("enlaceSiguiente").click();
}
}
</script>
I guess you were on the right track, but the problem is that your Javascript only gets executed once.我猜你是在正确的轨道上,但问题是你的 Javascript 只执行一次。 So, the else case will never be triggered.因此,永远不会触发 else 案例。 I refactored your code to use the check in the event listener:我重构了您的代码以使用事件侦听器中的检查:
var cont = 0;
var input = document.getElementById("respuestaUsuario");
input.addEventListener("keyup", function (event) {
if (event.keyCode == 13) {
event.preventDefault();
if (cont == 0) {
cont++;
document.getElementById("botonCorregir").click();
} else {
document.getElementById("enlaceSiguiente").click();
}
}
});
I also created a codepen for you to check out.我还创建了一个codepen供您查看。
You have a few mistakes in the code.您在代码中有一些错误。
You are assigning the event based on the value of cont so always will have that functionality.您根据cont的值分配事件,因此始终具有该功能。 Javascript does not re-interpret the code once the value of cont is changed.一旦cont的值改变,Javascript 不会重新解释代码。 I mean, Javascript check only one time the condition:我的意思是,Javascript 只检查一次条件:
if(cont==0){}
This is a solution that works:这是一个有效的解决方案:
var cont=0;
var input = document.getElementById('respuestaUsuario');
input.addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode == 13) {
if(!cont){
alert('uno');
document.getElementById("botonCorregir").click();
cont++;
}else{
document.getElementById("enlaceSiguiente").click();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.