Javascript 如何触发ESC按钮以清除文本框中输入的文本?

Javascript 如何触发ESC按钮以清除文本框中输入的文本?,javascript,html,css,Javascript,Html,Css,然后在您的输入标签中 function keyPressed(evt) { if (evt.keyCode == 27) { //clear your textbox content here... document.getElementById("search").value = ''; } } 声明一个在按键时调用的函数: <input type="text" onkeypress="keyPressed(event)" id="search" ...>

然后在您的输入标签中

function keyPressed(evt) {
 if (evt.keyCode == 27) {
    //clear your textbox content here...
    document.getElementById("search").value = '';
 }
}

声明一个在按键时调用的函数:

<input type="text" onkeypress="keyPressed(event)" id="search" ...>
以及相应的标记:

function onkeypressed(evt, input) {
    var code = evt.charCode || evt.keyCode;
    if (code == 27) {
        input.value = '';
    }
}


这应该行得通。

$('input[type=text]')。每个(函数(e){
$(此).keyup(函数(evt){
var代码=evt.charCode | | evt.keyCode;
如果(代码==27){
$(this.val(“”);
}
})
})


点击esc按钮查看结果

,非常感谢您的帮助Darin-我真的很感激:)Darin-如果您也能帮我解决这个问题:那太好了!达林:对于keydown事件,它总是
keyCode
。所有主要浏览器都有
keyCode
,因此无需检查
charCode
,在所有当前浏览器中该值均为零或未定义。感谢您的帮助Mamoo
onkeypress
未检测到escape、shift、箭头键等。必须是
onkeydown
onkeyup
<input type="text" onkeypress="keyPressed(event)" id="search" ...>
function onkeypressed(evt, input) {
    var code = evt.charCode || evt.keyCode;
    if (code == 27) {
        input.value = '';
    }
}
<input type="text" id="search" size="25" autocomplete="off" 
       onkeydown="onkeypressed(event, this);" />
<input type="text" value="" onkeyup="if ( event.keyCode == 27 ) this.value=''" />