I tried it but it seems like it can’t be transmitted? ? ?
習慣沉默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>
黄舟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...
给我你的怀抱2017-05-18 10:52:06
btn.addEventListener('click',function(){fn('params')});
function fn(data) {
alert(data)
}
Try this?
巴扎黑2017-05-18 10:52:06
document.getElementById('aaa').addEventListener('click', fn('asdadad'), false);
function fn(data) {
console.info(data);
}
巴扎黑2017-05-18 10:52:06
function foo(a, b, c) {}
// 不要这样做
setTimeout('foo(1,2, 3)', 1000)
// 可以使用匿名函数完成相同功能
setTimeout(function() {
foo(1, 2, 3);
}, 1000)
巴扎黑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
After thebtn.addEventListener('click',fn,false);
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.