简体   繁体   English

如何从JavaScript中的文本输入键调用功能?

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

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 This http://jsfiddle.net/abalter/adbbb599/6/ 添加了此 http://jsfiddle.net/abalter/adbbb599/6/

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>

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>

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. 您的“ this”是指输入字段,因此“ this.value”将返回输入字段的全部内容。 To get the keyCode from the keypress event try: 要从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. 因为未创建任何事件对象。

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

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