如何在代码中发送一个用作命令的语句?

时间:2016-03-29 20:29:44

标签: javascript

我一直想做的是传递oninputonmouseover之类的语句,然后将它们用作方法中的实际语句。

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>

有办法吗?

1 个答案:

答案 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