Home > Web Front-end > JS Tutorial > Detailed explanation of JS onkeypress compatibility writing method_javascript skills

Detailed explanation of JS onkeypress compatibility writing method_javascript skills

WBOY
Release: 2016-05-16 15:03:27
Original
1708 people have browsed it

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();
    }    
  });
  });
Copy after login

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();
  }

Copy after login

Description:

Read keyboard keys under IE:

keynum = event.keyCode; // 字母d,keynum=100
    keychar = String.fromCharCode(keynum); // 将keynum转换成字符d

Copy after login

Read keyboard keys in FireFox:

 keynum = event.which; // 字母d,keynum=100
    keychar = String.fromCharCode(keynum); // 将keynum转换成字符d
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template