2017-07-12 57 views
0

我定义了一个函数来更改元素属性。
我想在'addEventListener'中传递一个参数给这个函数,这是我的问题。在addeventlistener中传递一个参数 - javascript

下面是函数:

function collapse (el) { 
    var _cl = el.classList; 
    _cl.add("box_size1"); 
    el.removeAttribute("id"); 
} 

下面是主要代码:

window.onload = function() { 
    var el = document.getElementById("box_size2"); 
    el.addEventListener("click", collapse(???)); 
} 

我拿什么来写,而不是问号?

+0

https://developer.mozilla.org/en-US的/ docs/Web/API/EventTarget/addEventListener#The_value_of_this_within_the_handler – Phil

+0

[如何将参数传递给addEventListener中的函数?](https://stackoverflow.com/questions/12024483/how-to-pass-parameter-to -function-using-in-addeventlistener) – Xufox

+0

您是否搜索过“JavaScript如何将参数传递给Google中的addEventListener“? – Xufox

回答

2

无需通过任何与function.Default this在功能绑定。只是调用this的函数内el

window.onload = function() { 
 
var el = document.getElementById("box_size2"); 
 
el.addEventListener("click", collapse); 
 
} 
 

 
function collapse() { 
 
var _cl = this.classList; 
 
_cl.add("box_size1"); 
 
this.removeAttribute("id"); 
 
console.log(this.outerHTML) 
 
}
<button id="box_size2">click</button>

相关问题