Javascript How to use onclick function also with keyboard

旧巷老猫 提交于 2019-12-11 00:55:18

问题


I hope the title of the question fits to what I'm asking here.

I have this code in HTML & javascript:

<button id="Z">Z</button>

var btnZ = document.getElementById("Z");
btnZ.onclick = function() {
// Some code

Ok, now I want to execute btnZ.onclick function when the user press "Z" on keyboard. How can I do this without duplicating the code inside btnZ.onclick function?


回答1:


Use this:

function clicked () {
    alert('clicked!');
    //some code
}
document.onkeydown = function (e) {
    var keyCode = e.keyCode;
    if(keyCode == 90) {
        clicked();
    }
};
btnZ.onclick = clicked;



回答2:


You should have a common function which executes the code, but then have two event functions.

function do() {
     //some code
}
btnZ.onclick = function(e) {
    do();
};
btnZ.onkeydown = function(e) {
    var keyCode = e.keyCode;

    if(keyCode === 90) do();
}

This will only work if the user is focused on the element.




回答3:


If you can use HTML5, you can use the accesskey attribute (but it will respond to ALT + Z, and not Z only).

If you can't use HTML5, you must use the keydown event.




回答4:


You can declare the function separately and just refer to it wherever you need it. For example,

 var yourOnClickFunction =  function() {
                               // Some code
 btnZ.onclick = yourOnClickFunction;



回答5:


HTML

<button id="z">Z</button>

JS

document.onkeypress = function (e) { 
  e = e || window.event; 
  var charCode = e.charCode || e.keyCode, 
      character = String.fromCharCode(charCode); 

  if (character == 'z')
  alert(character);
};

document.getElementById('z').onclick = function (e){
    alert(document.getElementById('z').id)
}

JSFiddle




回答6:


One way is to trigger event of other element as shown in below example

<button >Hello</button>
clickButton = function(){
  alert("Hello clicked")
}
document.getElementsByTagName("button")[0].onclick = clickButton

keydown = function(e){
 if(e.keyCode==90)
   document.getElementsByTagName("button")[0].click()
}
document.onkeydown = keydown

if using JQuery you can use trigger function. Following is sample code and also find working example in codepen.io

<button >Hello</button>

$("button").click(function(){
  alert("Hello clicked")
})

$(document).keypress(function(e){
  if(e.charCode == 90)
    $("button").trigger("click")
})


来源:https://stackoverflow.com/questions/23800977/javascript-how-to-use-onclick-function-also-with-keyboard

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