Dynamically add 'onkeypress' event in JavaScript

Source: Internet
Author: User

The following code is used in the tutorial of helper House (www.bkjia.com). window. load = srchtxtAddOnKeyPress () is equivalent to the onload () event of the body. Generally, we place js in the head part of the page. However, here, if you put it in the head part, it is certainly wrong. Because the page loads js first and then <input type = "text" id = "srchtxt"/>, an error occurs during running. The system prompts that the srchtxt object cannot be found.

Reference content is as follows:
<Script language = "javascript" type = "text/javascript"> function srchtxtAddOnKeyPress () {if (window. addEventListener) {// event code of other browsers: Mozilla, Netscape, Firefox // the order of events added is the execution order // note that events with on are added with addEventListener, you do not need to add on document. getElementById ('srchtxt '). addEventListener ('keypress', keyPressEvt, false);} The Event code of else {// IE adds the add method document on the original event. getElementById ('srchtxt '). attachEvent ('onkeypress', keyPressEvt) ;}} function keyPressEvt () {if (event. keyCode = 13) {alert ('You press the enter key') ;}}; window. load = srchtxtAddOnKeyPress (); </script> <input type = "text" id = "srchtxt"/>

To solve this problem, we only need to add this code to the bottom of the page. That is to say, it can run smoothly after <input type = "text" id = "srchtxt"/>.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.