Yesterday, I encountered a problem when writing the last dynamically generated year, month, day drop-down box and text box restriction input. when entering the text box, I began to calculate the number of words entered in the text box, naturally, I thought of the onkeydown event and then calculated the value. length method. Check the code.
Copy codeThe Code is as follows:
Moto. onkeydown = function (){
Var curlen = + this. value. length;
Shuru. innerHTML = curlen;
Shuru2.innerHTML = + (200-curlen );
If (curlen> = 200 ){
This. value = this. value. substring (0,200 );
Curlen= 200;
Shuru. innerHTML = 200;
Shuru2.innerHTML = 0;
Return false;
}
}
The result shows that the number of words is incorrect after the text is entered. After the four words are entered, the number of words is displayed as 0.
After thinking about it for a long time, after changing onkeydown to onkeyup, everything will be fine.
Check whether the two events are different.
Onkeydown is triggered when it is pressed. At this time, the key value is not output. Onkeyup is executed when the key is lifted. At this time, the key value already exists. It does not matter how long it takes. For example, if you add the two events to the input box,
Copy codeThe Code is as follows:
<Input type = "text" id = "test1" onkeydown = "alert (this. value);"/>
<Input type = "text" id = "test2" onkeyup = "alert (this. value);"/>
You can see the two different running results!
Copy codeThe Code is as follows:
<! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
<Title> Insert title here </title>
</Head>
<Body>
<Input type = "text" id = "test1" onkeydown = "alert (this. value);"/>
<Input type = "text" id = "test2" onkeyup = "alert (this. value);"/>
</Body>
</Html>
Onkeydown is triggered when it is pressed. At this time, the key value is not output.
Onkeyup is executed when the key is lifted. At this time, the key value already exists.
It does not matter how long it takes. For example, if you add the two events to the input box,