我正在尝试对不同元素重用函数,有没有一种方法可以将我的代码用于onchange的不同输入元素。将此作为关键字传递或将参数保留为空都无济于事
function checksize() {
if (this.files[0].size > 2097152) {
alert("File is too big!");
this.value = "";
this.className = "is-invalid form-control-file";
} else {
this.className = "form-control-file"
};
}
<input onchange="checksize(this)" required accept=".jpg, .pdf, .jpg, .jpeg, .png" id="idfile" class="form-control-file" type="file" name="idfile">
答案 0 :(得分:0)
您可以使用bind
或this
call
apply
:
<input onchange="checksize.call(this)" required accept=".jpg, .pdf, .jpg, .jpeg, png" id="idfile" class="form-control-file" type="file" name="idfile">
答案 1 :(得分:0)
如果要使用this
。这可能是最简单的方法。
document.querySelectorAll("input[type='file']").forEach(function(input) {
input.addEventListener("click", function() {
checksize.call(input);
});
});
function checksize() {
console.log(this.id);
}
<input id="idfile1" type="file">
<input id="idfile2" type="file">
<input id="idfile3" type="file">
如果您愿意使用jQuery,可以执行以下操作:
$("input[type='file']").on("click", checksize);
function checksize() {
console.log(this.id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="idfile1" type="file">
<input id="idfile2" type="file">
<input id="idfile3" type="file">
答案 2 :(得分:0)
获取函数中传递的参数:
function checksize(that) {
if (that.files[0].size > 2097152) {
alert("File is too big!");
that.value = "";
that.className = "is-invalid form-control-file";
} else {
that.className = "form-control-file"
};
}
<input onchange="checksize(this)" required accept=".jpg, .pdf, .jpg, .jpeg, .png" id="idfile" class="form-control-file" type="file" name="idfile">
或者,您可以使用以下方法动态地附加事件,而不是在HTML中定义事件:
document.getElementById('idfile').addEventListener('change', checksize);
并使用您的函数(使用this
关键字):
document.getElementById('idfile').addEventListener('change', checksize);
function checksize() {
if (this.files[0].size > 2097152) {
alert("File is too big!");
this.value = "";
this.className = "is-invalid form-control-file";
} else {
this.className = "form-control-file"
};
}
<input required accept=".jpg, .pdf, .jpg, .jpeg, .png" id="idfile" class="form-control-file" type="file" name="idfile">
答案 3 :(得分:-2)
function checksize(event){
// use event to read ll files and read and write the element properties
if(this.files[0].size > 2097152){
alert("File is too big!");
this.value = "";
this.className = "is-invalid form-control-file";
}else{
this.className = "form-control-file"
};
}