javascript - btn.addEventListener('click',fn,false); How to pass parameters to fn?
我想大声告诉你
我想大声告诉你 2017-05-18 10:50:06
0
6
748

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

我想大声告诉你
我想大声告诉你

reply all(6)
習慣沉默

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>
黄舟

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...

给我你的怀抱
btn.addEventListener('click',function(){fn('params')});
function fn(data) {
    alert(data)
}

Try this?

巴扎黑
document.getElementById('aaa').addEventListener('click', fn('asdadad'), false);

function fn(data) {
    console.info(data);
}
巴扎黑
function foo(a, b, c) {}

// 不要这样做
setTimeout('foo(1,2, 3)', 1000)

// 可以使用匿名函数完成相同功能
setTimeout(function() {
    foo(1, 2, 3);
}, 1000)
巴扎黑

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template