2017-07-12 56 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>

相關問題