Javascript 如何从javascript中的文本输入按键调用函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28788896/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:25:43  来源:igfitidea点击:

How to call function from text input key press in javascript?

javascriptonkeypress

提问by abalter

With

<input type="text" onKeyPress="alert(this.value)">

the alert box displays the value in the box, not included the current key depressed.

警报框显示框中的值,不包括当前按下的键。

However, this does not exhibit the same behavior, and I don't know why.

但是,这并没有表现出相同的行为,我不知道为什么。

<input type="text" onKeyPress="handleInput(this.value)">

function handleInput(value){
    alert(value);
}

Added Thishttp://jsfiddle.net/abalter/adbbb599/6/

添加了这个http://jsfiddle.net/abalter/adbbb599/6/

回答by ismnoiet

First thing is avoid using js code inside html tags it is a bad practice , you can use the keyup event to get the content of the input after the user release any pressed key

首先是避免在 html 标签中使用 js 代码,这是一种不好的做法,您可以在用户释放任何按键后使用 keyup 事件获取输入的内容

<input id="input">

<script>
  var input = document.getElementById('input');
  input.addEventListener('keyup',function(){alert(input.value);});

</script>

回答by Kjell Ivar

It should exhibit the same behaviour. Make sure you load the javascript either in your head or body tags, so you can access the function from the html.

它应该表现出相同的行为。确保在 head 或 body 标签中加载 javascript,以便您可以从 html 访问该函数。

This code works for me:

这段代码对我有用:

<input type="text" onKeyPress="handleInput(this.value)">
    <script>
        function handleInput(value){
            alert(value);
        }
    </script>

回答by JMP

Passing 'value' as a parameter is generally verbotim - its a reserved word. Your 'this' refers to the input field, and so 'this.value' returns the entire content of the input field. To get the keyCode from the keypress event try:

将“值”作为参数传递通常是逐字逐句的——它是一个保留字。您的“this”指的是输入字段,因此“this.value”返回输入字段的全部内容。要从 keypress 事件中获取 keyCode,请尝试:

<body>
<input type="text" onKeyPress="handleInput();">
</body>
<script>
function handleInput(){
    alert(event.charCode);
}
</script>

This doesn't work with:

这不适用于:

onKeyPress="event.charCode;"

or:

或者:

onKeyPress="this.event.charCode;"

because no event object is created.

因为没有创建事件对象。