Today when registering events for elements, I encountered a problem using addEventListener. It seems that I have encountered this before. I feel it is necessary to summarize it. It is a problem caused by JS functions as parameters. First look at the following code. Do you think there is anything wrong with the following code? Is it possible to pop up id3 after clicking on the element corresponding to id3?
Example 1
var obj3=document.getElementById('id3'); obj3.addEventListener('click',curClick('id1'),true); function curClick(id){ alert(id); }
The answer is no, it cannot achieve the effect I want, because this line of code will ID3 will pop up. When I click on the element corresponding to id3, nothing happens on the page.
So I changed the code to the following two situations:
Example 2
var obj3=document.getElementById('id3'); obj3.addEventListener('click',function(e){curClick('id3');stopPropagation(e)},true); function curClick(id){ alert(id); }
Example 3
var obj1=document.getElementById('id1'); obj1.addEventListener('click',curClick1,true); function curClick1(){ alert('okey'); }
The execution is normal this time. Why is this?
Because in the JS world curClick('id3') directly calls curClick('id3') instead of passing it as a parameter. If you want to pass it as a parameter To pass, if you don’t need to pass parameters, just pass the function name directly. If you need to pass parameters, there are two solutions
Method 1: With the help of anonymous functions, the function to be passed, Place it in an anonymous function and use the anonymous function as a parameter. Example 2
#eg: function(){myfunction(val1,val2,...);} as a parameter transfer.
Second: Rewrite the function that needs to be passed
function curClick1(val){ <span style="white-space:pre"> </span>return function(){ alert(val); }; }
The above is a summary of passing a function as a parameter of another function in JS, more related content Please pay attention to the PHP Chinese website (m.sbmmt.com)!