Title rewrite: The function is called by addEventListener without my explicit request
P粉477369269
P粉477369269 2023-10-18 23:57:48
0
2
512

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粉477369269
P粉477369269

reply all(2)
P粉258083432

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粉773659687

Quoting Ian's Answer :

function message_me(m_text){
    alert(m_text)
} 

second.addEventListener('click', 
    function() {
        message_me('shazam');
    }
);

This is the updated fiddle.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!