简体   繁体   English

在单独的函数中跟踪输入字段中的用户按键

[英]track user key presses in input field in a separate function

I want to track user key presses in input field in a separate function and call a function based on onkeydown value.我想在单独的函数中跟踪输入字段中的用户按键并根据onkeydown值调用函数。 What I have below just doesn't work.我在下面的东西不起作用。 Nothing happens.什么都没发生。 I'm open to eye-opening revelations and commentary.我对令人大开眼界的启示和评论持开放态度。 I think I'm missing something major.我想我错过了一些重要的东西。

 function find_key(Fval, Fid) { //prevents malicious characters if ((event.charCode <= 47) || (event.charCode >= 64)) { return; }; // user presses ctrl + delete // this doesn't work, nothing happens if (event.code == 46 && (event.ctrlKey || event.metaKey)) { alert('Undo!'); } // user presses ctrl + enter // this doesn't work, nothing happens if (event.ctrlKey && e.keyCode == 13) { alert("grab"); grabName(Fval, Fid); } }
 <input onkeydown="find_key(this,this.id);" id="P${i}" />

I tried this based on a suggestion: (it doesn't work, though)我根据一个建议尝试了这个:(虽然它不起作用)

`<input class = 'tiger' id = "P${i}"  />`;

document.getElementsByClassName('tiger').addEventListener('keypress', findKey); document.getElementsByClassName('tiger').addEventListener('keypress', findKey);

function find_key (e) {

if (event.code == 46 && (event.ctrlKey || event.metaKey)) 
{ alert('Undo!'); }

You need to pass event as an argument (please note exact argument name "event" must be used).您需要将事件作为参数传递(请注意必须使用确切的参数名称“事件”)。

<input onkeydown = "find_key(event, this, this.id);" id = "P${i}"  />;

And then in js然后在js中

function find_key (event, Fval, Fid) {
    //...
}

PS why not using document method in js code and adding event listener to your input directly? PS 为什么不在 js 代码中使用 document 方法并直接将事件侦听器添加到您的输入中?

document.getElementById('input_el_id').addEventListener('keydown', findKey);

function findKey(e) {
    //...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM