有没有办法做||?或使用Jquery具有单击功能的语句?

时间:2019-10-23 03:32:13

标签: jquery onclick keycode

我想知道我是否可以通过单击div或按空格键来触发某个功能。我不记得看到过这样的功能了...有办法吗?

$('.button').click || keypress.keyCode === 32 (function() { 
    //do something
)};

4 个答案:

答案 0 :(得分:1)

赞:

$(function(){
    $('#div').on('keypress click', function(e){
    if (e.which === 32 || e.type === 'click') {

    }
  });
 });

Trigger an event on `click` and `enter`

答案 1 :(得分:1)

您可以通过使用div上的“ onclick”事件直接调用该函数。

<div onclick='invokeAFuntion' id='div-element'></div>

如果要在屏幕上的任意位置按下空格时触发功能,请使用文档元素作为选择器,否则请根据元素更改选择器。

$(document).on('keypress',function(e) {
    if(e.which == 32) {
        alert('You pressed enter!');
    }
});

function invokeAFuntion(){
 alert('You have invoked the function!');
}

答案 2 :(得分:1)

您也可以尝试此操作,也可以在此处查看在线演示Click here

注意:您可以处理globallyclick event中的任何keypress event

$(document).ready(function(){
  $(document).on('keypress click','button,input,textarea', function(e){
    if (e.which === 32 || (e.type === 'click' && e.currentTarget.localName =="button")) {
     console.log("which "+ e.which);
      console.log("Type "+ e.type);
      $("#result").html(" which "+ e.which + " Type "+ e.type);
      console.log($(this));
      console.log(e);
      console.log(e.currentTarget.localName);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-4" style="margin-bottom: 20px;">
 
  <input type="text"><br/>
  <button type="button">
  Click
  </button>
  <br/>
  <span id="result"></span>
</div>

请同时检查更新的小提琴链接Click here

答案 3 :(得分:0)

我能够通过创建两个单独的事件/函数来实现目标,但是让这些函数做同样的事情。

// If Button is Clicked
$('.button').click(function() { 
//do something
});

// If space bar is pressed
$(window).keypress(function (e) {
  if (e.keyCode === 32) {
    e.preventDefault()
//do same thing as if .button is clicked)
});