如何在JavaScript函数中传递文件元素

How to pass file element in JavaScript function

本文关键字:文件 元素 函数 JavaScript      更新时间:2023-09-26

我在我的应用程序中使用JavaScript在函数名cropper中,像这样

function cropper(){
var selectedImg = $('#image_file')[0].files[0];
}

我使用ID为image_file的文件元素从html中调用它,像这样

 <input type="file" id="image_file" name="picture1" onchange="cropper()"/><br>

我想把上面的函数改成

function cropper(variable){
var selectedImg = variable[0].files[0];
}

这样我就可以为不同的文件元素分配不同的ID。你能建议我如何才能实现上述功能吗?

编辑:

我的网站有4个文件附件按钮,我想为它使用不同的ID,所以它就像这样。

<input type="file" id="picture1" name="picture1" onchange="cropper(picture1)"/><br>
<input type="file" id="picture2" name="picture2" onchange="cropper(picture2)"/><br>
<input type="file" id="picture3" name="picture3" onchange="cropper(picture3)"/><br>
<input type="file" id="picture4" name="picture4" onchange="cropper(picture4)"/><br>

您可以将事件对象传递给处理程序

<input type="file" id="image_file" name="picture1" 
                                   onchange="cropper(event)"/><br>

然后使用方法

中的事件对象
function cropper(event){
   var selectedImg = event.target.files ? event.target.files[0]
                                        : $('#image_file')[0].files[0];
}
//variable = id of an element.
function cropper(variable){
     var selectedImg = $('#'+variable)[0].files[0];
}