Javascript的addEventListener如何傳遞參數?
在練習javascript的dynamic object時,想為div加一個click event,call一個function,例如
var x = document.createElement("div");
x.addEventListener("click", some_function(some_parameter) );
some_function(y){
alert(y);
}
發現會在載入時觸發而非點擊時觸發,google後找到How to pass arguments to addEventListener listener function?
頭幾個答案也用不上,被採納的回答也有問題—只會將loop後的值傳到function內,而並非在loop運行時,直到這個答案:
You can just bind all necessary arguments with 'bind':root.addEventListener('click', myPrettyHandler.bind(null, event, arg1, ... ));
In this way you'll always get theevent
,arg1
, and other stuff passed tomyPrettyHandler
.
http://passy.svbtle.com/partial-application-in-javascript-using-bind
原來是要用Function.prototype.bind() ,用法為:
function.bind(thisArg[, arg1[, arg2[, ...]]])
bind()
方法,會建立一個新函式。該函式被呼叫時,會將this
關鍵字設為給定的參數,並在呼叫時,帶有提供之前,給定順序的參數。
ref:https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
最後寫成:
var x = document.createElement("div");
x.addEventListener("click", some_function.bind(null,some_parameter) );