gpt4 book ai didi

javascript - onKeyPress 函数没有被立即调用

转载 作者:行者123 更新时间:2023-11-29 18:02:34 25 4
gpt4 key购买 nike

    document.getElementById('my').onkeypress = function(event) {
this.value = this.value.toUpperCase()
}
    <input id='my' type="text">

谁能给我解释一下上面代码中的this 变量指向什么?它是否指向我从 document.getElementById('my) 中获取的输入 html 元素?还是指向浏览器中的window对象?另外传递给匿名函数的event参数是什么?

出于某种原因,当我运行这段代码时,除了最后一个字符外,每个字符的值都是大写的。因此,例如当我输入:字符 a 不会立即大写,只有在我输入另一个字母时才会大写。例如:抗体。现在 b 不是大写的,直到我在 b 之后输入另一个字母:ABc。这还在继续。有人可以解释为什么会这样吗?

最佳答案

Can someone explain to me what the this variable points to in the code above? Does it point to the input html element I grabbed from the document.getElementById('my)? Or does it point to the window object in the browser? Also what is the 'event' parameter passed into the anonymous function?

  • this 指的是输入元素
  • 不是匿名函数,是onkeypress函数的声明
  • event 是上述函数的参数 more info

意想不到的(?)行为是因为代码是在输入字段更新之前执行的,所以只有以前的值被大写。为避免这种情况,您可以使用 onkeyup 事件,该事件在您释放按键后触发。

看这里:

document.getElementById('my').onkeypress = function(event) {
this.value = this.value.toUpperCase()
}

document.getElementById('my2').onkeyup = function(event) {
this.value = this.value.toUpperCase()
}

document.getElementById('my3').oninput = function(event) {
this.value = this.value.toUpperCase()
}
<input id='my' type="text" placeholder="onkeypress">
<input id='my2' type="text" placeholder="onkeyup">
<input id='my3' type="text" placeholder="oninput">

感谢 @www139 在评论中提出 oninput,因为它确实是现代浏览器的最佳解决方案 请注意它仅适用于 HTML5,您无法获得关键代码、标识符等信息...

关于javascript - onKeyPress 函数没有被立即调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33848313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com