Home >Web Front-end >JS Tutorial >Detailed explanation of JS onkeypress compatibility writing method_javascript skills
It is required to enter the password and press Enter to trigger the background event. It seems to be a very simple requirement, but it encounters many problems.
The HTML content mainly includes a password input text box and a button to trigger background events.
1. After the TextBox text box gets focus, just press Enter and the page will refresh.
After careful study of the code, it turns out that when there is only one text box control on the page, the page will be refreshed when pressing Enter.
Solution: Add a hidden TextBox control to the page.
The specific principle is unknown!
2. Use Jquery to implement the method:
$(document).ready(function(){ $("#tbPassword").focus(); $('#bPassword').keydown(function(e){ if(e.keyCode == 13){ $("#ctl00_ContentBody_btnAccept_linkButton")[0].click(); } }); });
3. Due to various reasons, the Jquery implementation method cannot be used, so we have to use JS instead. Its compatibility is the most troublesome issue.
document.getElementByIdx_x_x("tbPassword").onkeypress = function(event){ var keynum; if(window.event) // IE { keynum = window.event.keyCode; } else if(event.which) // Netscape/Firefox/Opera { keynum = event.which; } if (keynum == 13) document.getElementByIdx_x_x('ctl00_ContentBody_btnAccept_linkButton').click(); }
Description:
Read keyboard keys under IE:
keynum = event.keyCode; // 字母d,keynum=100 keychar = String.fromCharCode(keynum); // 将keynum转换成字符d
Read keyboard keys in FireFox:
keynum = event.which; // 字母d,keynum=100 keychar = String.fromCharCode(keynum); // 将keynum转换成字符d
For example, in IE, there is only the keyCode attribute, while in FireFox, there are which and charCode attributes, and in Opera, there are keyCode and which attributes, etc.
Therefore, this compatibility issue has been solved in Jquery.
The above is the entire content of this article, I hope it will be helpful to everyone’s study.