我在我的应用程序中使用 JavaScript,就像那样的函数名称裁剪器
function cropper(){
var selectedImg = $('#image_file')[0].files[0];
}
我像这样使用我的 html 中 ID 为 image_file 的文件元素来调用它
<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];
}
关于javascript - 如何在 JavaScript 函数中传递文件元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16929874/