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"/>.