So we have a page:
<span id='container'> <a href='#' id='first'>First Link</a> <a href='#' id='second'>Second Link</a> </span>
and want to add some click events:
first.addEventLis tener('click', function(){alert('sup!');})
Works like a charm! However, when you set the second argument to an external function:
function message_me(m_text){ alert(m_text) } second.addEventLis tener('click', message_me('shazam'))
It calls the function immediately. How can I stop this? So annoying!
This is a live demo: http://jsfiddle.net/ey7pB/1/
P粉2580834322023-10-19 17:48:17
Since the second parameter requires a function reference , you need to provide one. With the code in question, you would immediately call the function and pass its result (which is undefined
...because all the function does is alert
and returns nothing). Either call the function in an anonymous function (like your first example) or change the function to return a function.
You can do this:
function message_me(m_text){ alert(m_text); } second.addEventListener('click', function () { message_me('shazam') });
Or this:
function message_me(m_text){ return function () { alert(m_text); }; } second.addEventListener('click', message_me('shazam'));
Demo: http://jsfiddle.net/tcCvw/ p>
P粉7736596872023-10-19 12:06:48
Quoting Ian's Answer :
function message_me(m_text){ alert(m_text) } second.addEventListener('click', function() { message_me('shazam'); } );
This is the updated fiddle.