不論是何種語言或script,傳遞參數到event一直都是比較困難且難以理解的工作,以下是javascript中
透過回傳function來解決傳遞參數到event的問題
。
傳遞值var a = document.getElementsByTagName("input");
for (var i=0; i<a.length;i++) {
a[i].onclick = function(idx) {
return function(e) {
alert(idx);
};
}(i);
}
傳遞nodefunction handle() {
this.abc = "def";
this.setHandler = function(obj) {
obj.onclick = function(that) {
return function() {
alert(that.abc);
};
}(this);
}
}
var a = new handle();
a.setHandler(document.getElementsByTagName('input')[0]);
setTimeoutfunction handle() {
this.abc = "def";
this.delayMsg = function(m) {
setTimeout(function(a){
return function(e){
alert(a.abc);
};
}(this), m);
};
}
var a = new handle();
a.delayMsg(600);