Jquery binding key to body except a class

萝らか妹 提交于 2021-02-10 19:54:23

问题


I'm trying to bind a key to my entire page except to one class of elements.

$('*').not('.textarea-note').keypress(function (event) {
    // if key pressed is space
    if (event.which == 32) {
        alert('space pressed');
        event.preventDefault();
    }
});

The problem is that I need to do the preventDefault() and when I'm in a textarea then I can't make a space caracter.

Am I doing something wrong or it's not possible to bind to everything except some class or something.

Thanks in advance !

Edit :

After the comment from Roland, I came up with this instead which is working perfectly.

$(document).keypress(function (event) {
    // if key pressed is space
    if (event.which == 32 && event.target.nodeName != "TEXTAREA") {
        if (videoPlaying) {
            pauseVideo();
        } else {
            playVideo();
        }
        event.preventDefault();
    }
});

回答1:


I think you are looking for this...

$(document).keypress(function(event) {
  // if key pressed is space
  if (event.which == 32) {



    if (event.target.id !== "a1") {// for class $(event.target).attr('class')
      alert('space pressed');
      event.preventDefault();
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<textarea id="a1"></textarea>
<textarea id="a2"></textarea>
<textarea id="a3"></textarea>


来源:https://stackoverflow.com/questions/33918672/jquery-binding-key-to-body-except-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!