addEventListener calls the function without me even asking it to

前端 未结 4 555
故里飘歌
故里飘歌 2020-11-22 02:37

So we have a page:


    First Link
    Second Link&         


        
相关标签:
4条回答
  • 2020-11-22 03:07

    or you can use .bind

    function message_me(m_text){
        alert(m_text);
    }
    
    second.addEventListener('click', message_me.bind(this, 'shazam'));
    

    check MDN Documentation about 'closures'

    0 讨论(0)
  • 2020-11-22 03:08

    Modern ES6 solution using arrow functions

    second.addEventListener('click', () => message_me('shazam'))
    
    0 讨论(0)
  • 2020-11-22 03:14

    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter 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/

    0 讨论(0)
  • 2020-11-22 03:17

    Quoting Ian's answer:

    Since the second parameter expects a function reference, you need to provide one. With your problematic code, you're immediately calling the function and passing its result (which is undefined...because all the function does is alert and doesn't return anything). Either call the function in an anonymous function (like your first example) or alter the function to return a function.

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

    Here's an updated fiddle.

    0 讨论(0)
提交回复
热议问题