我一直想做的是传递oninput
或onmouseover
之类的语句,然后将它们用作方法中的实际语句。
function Controller() {
this.listen = function(elem, func, statement) {
elem.statement = function() {//and then use it here
func(elem);
};
return true;
};
}
var age = document.getElementById('age');
var controller = new Controller();
controller.listen(age, callMe, oninput);//set the statement here
function callMe(elem) {
console.log('hey');
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<input type="number" id="age" />
</body>
</html>
有办法吗?
答案 0 :(得分:2)
将oninput
作为字符串("oninput"
)传递,然后使用方括号访问elem
的属性:
function Controller() {
this.listen = function(elem, func, statement) {
elem[statement] = function() {//and then use it here
func(elem);
};
return true;
};
}
var age = document.getElementById('age');
var controller = new Controller();
controller.listen(age, callMe, "oninput");//set the statement here
function callMe(elem) {
console.log('hey');
}
但是,我建议您使用element.addEventListener()
代替.onevent
,请参阅addEventListener vs onclick。