search

Home  >  Q&A  >  body text

javascript - btn.addEventListener('click',fn,false); How to pass parameters to fn?

I tried it but it seems like it can’t be transmitted? ? ?

我想大声告诉你我想大声告诉你2755 days ago749

reply all(6)I'll reply

  • 習慣沉默

    習慣沉默2017-05-18 10:52:06

    Why do so many people dislike it? I think it’s a good problem. Closure can solve it

    <button>click</button>
    <script>
        document.querySelector("button").addEventListener("click", fn('hello world'), false);
        
        function fn(a) {
            return function() {
                alert(a);
            }
        }
    </script>

    reply
    0
  • 黄舟

    黄舟2017-05-18 10:52:06

    I don’t know what you want to send.

    But you can define fn as a function that returns a function. Basically meet the needs...

    reply
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-18 10:52:06

    btn.addEventListener('click',function(){fn('params')});
    function fn(data) {
        alert(data)
    }

    Try this?

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-18 10:52:06

    document.getElementById('aaa').addEventListener('click', fn('asdadad'), false);
    
    function fn(data) {
        console.info(data);
    }

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-18 10:52:06

    function foo(a, b, c) {}
    
    // 不要这样做
    setTimeout('foo(1,2, 3)', 1000)
    
    // 可以使用匿名函数完成相同功能
    setTimeout(function() {
        foo(1, 2, 3);
    }, 1000)

    reply
    0
  • 巴扎黑

    巴扎黑2017-05-18 10:52:06

    I didn’t find the function prototype of addEventListener. In daily use, my feeling is that it is. After
    addEventListener captures the trigger event, add () to the calling function name to call .
    Then

    btn.addEventListener('click',fn,false);

    After the

    listening event addEventListener captures the click event, the function executed is fn()
    addEventListener has the disadvantage that it cannot add parentheses with parameters, that is, it cannot capture the click and then execute fn(1,2).
    So usually, I use an anonymous function function(){fn(1,2)} as the binding function. Then the code becomes like this:

    btn.addEventListener('click',function(){fn(1,2)},false)

    After capturing the click event, the triggered function is
    function(){fn(1,2)}()
    You can trigger a parameterized function like fn(1,2).

    I’m not very familiar with the addEventListener function, welcome to discuss and correct me.

    reply
    0
  • Cancelreply