我一直在尝试做的是传递像 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>
有办法做到这一点吗?
最佳答案
将 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 .
关于javascript - 如何发送一条语句以用作代码中的命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36294508/