SoFunction
Updated on 2025-02-28

JS assigns value to onclick event, dynamically pass parameter instance explanation

Let's take a look at the wrong examples
Html code
Copy the codeThe code is as follows:

<body>
<input type="text" value="123456" >
<input type="button" value="button" onclick="">
</body>

Javascript code
Copy the codeThe code is as follows:

<script>
function show(value)
{
alert(value);
}

= show();
<script>

There are errors in executing the above code, because the show() sentence directly executes the show method, and the method object is not assigned to the event correctly.
If we change this
Copy the codeThe code is as follows:

= show;

Parameters cannot be passed.
So the correct code should be written like this, we add a parameter to see more clearly:
Html code
Copy the codeThe code is as follows:

<body>
<input type="text" value="123456" >
<input type="button" value="button" onclick="">
</body>

Javascript code
Copy the codeThe code is as follows:

<script>
function show(value1,value2)
{
alert(value1+","+value2);
}

var i = 10;
= function(){
show(,i);
};
<script>

This implements dynamic assignment of onclick event handles and supports parameter passing.