With
<input type="text" onKeyPress="alert(this.value)">
警告框显示的是框中的值,不包括当前按下的键。然而,这种行为并不相同,我不知道为什么。
<input type="text" onKeyPress="handleInput(this.value)">
function handleInput(value){
alert(value);
}
With
<input type="text" onKeyPress="alert(this.value)">
<input type="text" onKeyPress="handleInput(this.value)">
function handleInput(value){
alert(value);
}
首先,避免在HTML标签内使用JS代码,这是一种不好的做法。你可以使用keyup事件,在用户释放任何按键后获取输入内容。
<input id="input">
<script>
var input = document.getElementById('input');
input.addEventListener('keyup',function(){alert(input.value);});
</script>
它应该表现出相同的行为。 确保你在head或body标签中加载javascript,这样你就可以从html访问函数。
这段代码对我有效:
<input type="text" onKeyPress="handleInput(this.value)">
<script>
function handleInput(value){
alert(value);
}
</script>
<script src="/path/file.js"></script>
即可,但我同意@hamism的观点,最好避免将JS代码放在HTML标签中。 - Kjell Ivar<body>
<input type="text" onKeyPress="handleInput();">
</body>
<script>
function handleInput(){
alert(event.charCode);
}
</script>
这不适用于:
onKeyPress="event.charCode;"
或者:
onKeyPress="this.event.charCode;"