gpt4 book ai didi

javascript - 如何发送一条语句以用作代码中的命令?

转载 作者:行者123 更新时间:2023-12-02 14:49:32 25 4
gpt4 key购买 nike

我一直在尝试做的是传递像 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>

有办法做到这一点吗?

最佳答案

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com