我如何禁用第二次在jquery中按相同的键?

时间:2018-08-06 16:28:49

标签: javascript jquery events javascript-events key

第一次按37时,它显示警报消息,第二次再次按相同的键,我想禁用该键。该怎么办?

$(document).on (‘keydown’ , function (e){
var userVal = e.which ∥ e.keycode
valadation (userVal)

})

function valadation (userVal){
if (37 == userVal){
alert (“Wecome”)
 }
}

2 个答案:

答案 0 :(得分:0)

                                        //name the handler
$(document.body).on('keydown', function alertOnEnter (e) {
  if ([e.keyCode, e.which].indexOf(13) > -1) {
                     //remove the handler from the event
    $(document.body).off('keydown', alertOnEnter);
    alert('you hit enter');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:0)

创建一个变量并更新其值。

let clickVar = 0
$(document).on('keydown', function(e) {

  var userVal = e.which || e.keycode
  valadation(userVal)

})

function valadation(userVal) {

  if (37 === userVal && clickVar === 0) {
    alert('Welcome');
    clickVar++
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>