我一直在清理我的 js 代码,我想知道是否可以以通用方式使用事件。
我有一个响应 oninput
事件的表单
现在我对每个输入字段都有一个关于事件应该做什么的具体说明。
这是我的 JavaScript 代码:
firstname.oninput = function () {
updatePreview();
updatePostHeader();
showPreview();
};
lastname.oninput = function () {
updatePreview();
showPreview();
};
age.oninput = function () {
updatePreview();
showPreview();
};
job.oninput = function () {
updatePreview();
showPreview();
};
avatar.oninput = function () {
updateAvatar();
showPreview();
};
message.oninput = function () {
updatePreview();
showPreview();
};
如您所见,它有很多冗余。
我可以像下面那样简化它吗?
for(var i=0; i<inputFields.length; i++) {
inputFields[i].oninput = function() {
updatePreview();
showPreview();
};
}
最佳答案
我不太确定您是如何获取变量的,例如:lastname
、age
等。但是最干净的方法是像您建议的那样将它们放入一个数组中。喜欢:
var controlIds = [
{"id": 'id1', "functions": [updatePreview, showPreview]},
{"id": 'id2', "functions": [updatePreview, updatePostHeader, showPreview]}
];
controlIds.map(function (item){
item["element"] = document.getElementById(item["id"]);
return item;
}).forEach(function(elem) {
elem["element"].oninput = function () {
elem["functions"].forEach(function(fn) { fn(); });
}
});
关于javascript - 以更短的方式使用事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28529671/