触发 <input type="file"/> 的 javascript 事件 onchange 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12383968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fire javascript event onchange event of <input type="file"/>
提问by xaero
I have this code
我有这个代码
<input id="fileupload"
type="file" name="files[]"
class="inputFile clickable"
onchange="uploadFile(this.value)"/>
This works fine on second time using it, i.e. first time I select the file the onchange event does not fire, but selecting file for the second time works fine.
这在第二次使用时效果很好,即第一次选择文件时 onchange 事件不会触发,但第二次选择文件效果很好。
Is there any thing which I can change here?
有什么我可以在这里改变的吗?
I have tried:
我努力了:
onlclick
(doesn't work, fires before selecting file)onblur
(doesn't work, doesn't fire at all, plus even if does, its just stupid to click somewhere else on page to fire the operation)onselect
(doesn't work)
onlclick
(不起作用,在选择文件之前触发)onblur
(不起作用,根本不触发,而且即使触发,点击页面上的其他地方来触发操作也是愚蠢的)onselect
(不起作用)
Additional info:
If I use onchange=alert(this.value)
it works fine
附加信息:如果我使用onchange=alert(this.value)
它工作正常
this is my javascript code
这是我的 javascript 代码
function uploadFile(value) {
alert(value); //works fine
$('#fileupload').fileupload({
dataType: 'json',
url: 'fileUpload.php',
type: 'POST',
limitConcurrentUploads: 1,
// done: function (e, data) {
// $.each(data.result, function (index, file) {
// $('<p/>').text(file.name).appendTo(document.body);
// });
// },
success: function() {
showMultipleDataDiv(value); //but I don't get value here
}
});
}
回答by Rodrigo5244
The code $('#fileupload').fileupload
will trigger a file upload as soon as the user selects a file. You need to run this code before the user selects a file, because it adds an event listener to the input tag. Since you only run this code after the user selects a file, then it will only work on the second time.
$('#fileupload').fileupload
一旦用户选择一个文件,该代码将触发文件上传。您需要在用户选择文件之前运行此代码,因为它向输入标记添加了一个事件侦听器。由于您仅在用户选择文件后运行此代码,因此它只会在第二次运行。
This is the change you need to do to make it work
这是您需要做的更改才能使其工作
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: 'fileUpload.php',
type: 'POST',
limitConcurrentUploads: 1,
// done: function (e, data) {
// $.each(data.result, function (index, file) {
// $('<p/>').text(file.name).appendTo(document.body);
// });
// },
success: function () {
showMultipleDataDiv(value); //but I don't get value here
}
});
});
Notice there is no need to add code in the change event. The plugin is going to do that for you.
请注意,无需在更改事件中添加代码。该插件将为您做到这一点。
You can read more about it here: https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin
您可以在此处阅读更多相关信息:https: //github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin