How JavaScript passes parameters to event handlers:
You may need to pass parameters to the registered event handler in your application, but you will find that it is not possible to implement direct delivery, so here's a quick introduction to how to pass parameters to the event handler function.
Let's look at a code example:
<!DOCTYPE HTML> <HTML> <Head> <MetaCharSet= "Utf-8"> <Metaname= "Author"content= "http://www.softwhy.com/" /><Head><title>Ant Tribe</title> <Scripttype= "Text/javascript"> functionmytest (num) {alert (num);} Window.onload=function(){ varBT=document.getElementById ("BT"); Bt.onclick=mytest (1);}</Script> </Head> <Body> <inputtype= "button"value= "Click Test Effect"ID= "BT"></Body> </HTML>
The code above is meant to be able to pass a parameter to the function when the button is clicked, but this is wrong, because the function executes directly.
Correct wording:
Way One:
<!DOCTYPE HTML> <HTML> <Head> <MetaCharSet= "Utf-8"> <Metaname= "Author"content= "http://www.softwhy.com/" /><Head><title>Ant Tribe</title> <Scripttype= "Text/javascript"> functionmytest (num) {alert (num);} Window.onload=function(){ varBT=document.getElementById ("BT"); Bt.onclick=function() {mytest (1) }}</Script> </Head> <Body> <inputtype= "button"value= "Click Test Effect"ID= "BT"></Body> </HTML>
Nested functions are called in the event handler so that the arguments can be passed.
Way two:
<!DOCTYPE HTML> <HTML> <Head> <MetaCharSet= "Utf-8"> <Metaname= "Author"content= "http://www.softwhy.com/" /><Head><title>Ant Tribe</title> <Scripttype= "Text/javascript"> functionmytest (num) {alert (num);}</Script> </Head> <Body> <inputtype= "button"value= "Click Test Effect"OnClick= "mytest (1)"/></Body> </HTML>
The principle of this way and way one is the same.
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=8234
For more information, refer to: http://www.softwhy.com/javascript/
How JavaScript passes parameters to event handlers