简体   繁体   English

如何将jQuery代码转换为JavaScript?

[英]How can I convert this jQuery code to JavaScript?

I want convert following working jQuery code into JavaScript 我想将以下有效的jQuery代码转换为JavaScript

$(document).ready(function(){
    $("#txt1").keydown(function(event){
        var keyPress=String.fromCharCode(event.keyCode);
        var Keycode=event.keyCode;
        alert("KeyPress : "+keyPress)
        alert("KeyCode : "+Keycode)   
    })
})

and I am trying this to replace this code with JavaScript 我正在尝试用JavaScript替换此代码

document.getElementById("txt1").onkeydown=function(event){
    var keyPress=String.fromCharCode(event.keyCode);
    var Keycode=event.keyCode;
    alert("KeyPress : "+keyPress)
    alert("KeyCode : "+Keycode) 
}

and this above code not working. 上面的代码不起作用。

Try this: 尝试这个:

window.onload = function() {
  document.getElementById("txt1").addEventListener("keydown", function(e) {
    keyPress = String.fromCharCode(e.keyCode);
    keyCode = e.keyCode;    
    alert("KeyPress : " + keyPress)
    alert("KeyCode : " + keyCode)  
  }, false);
}

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

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