Javascript How to use onclick function also with k

2019-07-19 02:33发布

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?

6条回答
Luminary・发光体
2楼-- · 2019-07-19 02:51

Use this:

function clicked () {
    alert('clicked!');
    //some code
}
document.onkeydown = function (e) {
    var keyCode = e.keyCode;
    if(keyCode == 90) {
        clicked();
    }
};
btnZ.onclick = clicked;
查看更多
来,给爷笑一个
3楼-- · 2019-07-19 02:52

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楼-- · 2019-07-19 02:57

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")
})
查看更多
戒情不戒烟
5楼-- · 2019-07-19 02:59

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楼-- · 2019-07-19 03:16

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.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-07-19 03:16

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;
查看更多
登录 后发表回答