gpt4 book ai didi

javascript - 如何删除 DOM 事件处理程序的重复 JavaScript 代码?

转载 作者:行者123 更新时间:2023-11-29 09:55:51 25 4
gpt4 key购买 nike

我正在尝试删除重复的 JavaScript 代码。我有一个页面有很多 <input type="file"> .每个加载图像并执行一些不同的处理。问题是我有很多重复的以下代码:

inputFile1.onchange = function (e) {
var file = e.target.files[0];
if (typeof file == 'undefined' || file == null) {
return;
}
var imageType = /image.*/;
if (!file.type.match(imageType)) {
window.alert('Bad file type!');
return;
}
var reader = new FileReader();
reader.onloadend = function (e) {
var imageLoader = new Image();
imageLoader.onload = function () {
// process image
};
imageLoader.src = e.target.result;
};
reader.readAsDataURL(file);
};

inputFile2.onchange = ... (repeats all but process image)
inputFile3.onchange = ... (repeats all but process image)

只有 process image 处的代码评论各不相同。如何删除周围的重复代码?

我知道 JavaScript 函数是对象。我如何定义一个函数对象并为每个事件处理程序创建一个不同的实例,为 process image 传递不同的函数?每个对象?

最佳答案

您可以为此类函数创建一个生成器,并使用一个闭包将单个回调作为参数:

function getChangeHandler(loadCallback) {
return function (e) {
var file = e.target.files[0];
if (typeof file == 'undefined' || file == null) {
return;
}
var imageType = /image.*/;
if (!file.type.match(imageType)) {
window.alert('Bad file type!');
return;
}
var reader = new FileReader();
reader.onloadend = function (e) {
var imageLoader = new Image();
imageLoader.onload = loadCallback; // <= uses the closure argument
imageLoader.src = e.target.result;
};
reader.readAsDataURL(file);
};
}
inputFile1.onchange = getChangeHandler(function() { /* custom process image */ });
inputFile2.onchange = getChangeHandler(function() { /* custom process image */ });
inputFile3.onchange = getChangeHandler(function() { /* custom process image */ });

另一种最终更好的方法是对所有输入仅使用一个 change 事件处理程序,它通过 name 动态选择自定义图像处理器>输入的id:

var imageProcessors = {
"box1": function() { … },
"anotherbox": function() { … },

};
function changeHandler(e) {
var input = this; // === e.target

reader.onloadend = function (e) {

imageLoader.onload = imageProcessors[input.id];
};
}
// and bind this one function on all inputs (jQuery-style):
$("#box1, #anotherbox, …").click(changeHandler);

关于javascript - 如何删除 DOM 事件处理程序的重复 JavaScript 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11820115/

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