最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detect key pressed in text input from onkeydown() inline function - Stack Overflow

programmeradmin4浏览0评论

I have the following

<input name='blah[]' onkeydown="itemKeyDown(this)">

Is it possible to detect what key was pressed in the itemKeyDown() function?

I tried the usual approach with:

e.keyCode || e.which

but it returns undefined.

To note: I could do it the jQuery way, but I needed to specifically attach the function call in the HTML code (inside the tags) because I'm dynamically generating a lot of copies of this text field, and this way all fields generated will inherit the function call. I don't want to have to bind a listener to a text field, all are generated.

I have the following

<input name='blah[]' onkeydown="itemKeyDown(this)">

Is it possible to detect what key was pressed in the itemKeyDown() function?

I tried the usual approach with:

e.keyCode || e.which

but it returns undefined.

To note: I could do it the jQuery way, but I needed to specifically attach the function call in the HTML code (inside the tags) because I'm dynamically generating a lot of copies of this text field, and this way all fields generated will inherit the function call. I don't want to have to bind a listener to a text field, all are generated.

Share Improve this question edited Mar 12, 2024 at 13:06 Mark Rotteveel 110k229 gold badges156 silver badges224 bronze badges asked Apr 16, 2017 at 14:24 BrownChiLDBrownChiLD 3,74310 gold badges47 silver badges64 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

Like that?

function itemKeyDown(e) {
    console.log(e.keyCode || e.which);
}
<input name='blah[]' onkeydown="itemKeyDown(event)">

<input name='blah[]' onkeydown="itemKeyDown(this)">

this keyword doesn't carry any information about the event onkeydown it represent the DOM element (input)

to get the event data you should pass event keyword like:

<input name='blah[]' onkeydown="itemKeyDown(event)">

<script>
function itemKeyDown(e)
{
  console.log(e.keyCode)
}

</script>

发布评论

评论列表(0)

  1. 暂无评论