JScript/JavaScript has very few reference documents and is not very detailed. Many syntaxes are just a bit confusing. Today I encountered a problem when writing event functions, which is discussed as follows.
As we all know, there are multiple methods to write HTML element events. Code :
1. directly write the on ??? Attribute, such:
< Input Type = "Button" Onclick = "Alert ('clicked! ')" Value = "Click me! " >
Or
< Input Type = "Button" Onclick = "Alerter ()" Value = "Click me! " >
Here, Alerter () is a written JScript function.
2. Use the event attributes of the HTML element object, such:
< Input ID = "Button1" Type = "Button" Value = "Click me! " >
< Script Language = "JavaScript" >
Button1.onclick = Alerter
Function Alerter ()
{
Window. Alert ("You clicked the button!")
}
</ Script >
3. Use <script for>, for example: < Input ID = "Button1" Type = "Button" Value = "Click me! " >
< Script For = "Button1" Event = "Onclick" Language = "JavaScript" >
Alert ("You clicked the button!")
</ Script >
4. Use the attachevent function, for example: < Input ID = "Button1" Type = "Button" Value = "Click me! " >
< Script Language = "JavaScript" >
Button1.attachevent ( " Onclick " , Alerter)
Function Alerter ()
{
Window. Alert ("You clicked the button!")
}
</ Script >
The commonly used methods are 1st and 2, but sometimes the 2nd method is quite suitable. For example, when writing body. onload, it is not necessarily convenient to write the onload attribute in the <body> element. In particular, when you write a Web user control (. ascx) in ASP. NET, it does not have a <body> element. So I wrote the following Script: Window. Onload=Alert ("Load!");
We are happy to find that it can also run without errors. However, it is strange that its next statement will not always be executed. For example, there will be another alert ("hi"); after opening the webpage, only one prompt "load!" will be displayed !" The "hi" dialog box does not appear ". In addition, "Hi" should appear first, and then "LOAD.
Originally, according to method 2, the event function cannot contain parameters! Only window. onload = funcname; can be written. To call one or more functions with parameters, you can write these statements into one function. You can also write it as follows:
Window. onload = Function () {Alert ("Load!");} ;
This is equivalent to generating an anonymous function. However, the window. onload statement is already incorrect, and the following statement will not be executed again.
It seems that you should be cautious when thinking about the problem.