Javascript 使用带有.change()事件的输入type=“file”字段上载文件在IE和Chrome中并不总是触发
我有一段简单的代码来上传文件:Javascript 使用带有.change()事件的输入type=“file”字段上载文件在IE和Chrome中并不总是触发,javascript,jquery,internet-explorer,firefox,google-chrome,Javascript,Jquery,Internet Explorer,Firefox,Google Chrome,我有一段简单的代码来上传文件: $(document).ready(function () { $(".attachmentsUpload input.file").change(function () { $('form').submit(); }); }); <form class="attachmentsUpload" action="/UploadHandler.ashx" method="post" enctype="multipart/form
$(document).ready(function () {
$(".attachmentsUpload input.file").change(function () {
$('form').submit();
});
});
<form class="attachmentsUpload" action="/UploadHandler.ashx" method="post" enctype="multipart/form-data">
<input type="file" class="file" name="file" />
</form>
当我点击输入,然后在对话框中选择一个文件时,我正在使用ajax提交这个文件。这不是这里重要的部分。重要的一点是,当我在对话框中第二次选择相同的文件时,在提交第一个文件之后,.change事件不会在IE和Chrome中触发。但是,当我选择不同的文件时,事件会激发并正常工作。在Firefox下,它一直在启动
如何解决此问题,使其与Firefox中的预期一样工作?说明
发生这种情况的原因是,如果再次选择同一文件,则所选文件路径的输入字段的值不会更改
您可以将onChange事件中的值设置为空字符串,并仅在该值不为空时提交表单。看看我的样品和这个
样品
使现代化
无论出于何种原因,这在IE9中都不起作用。您可以替换元素以重置它们。
在这种情况下,您需要jQuery live来绑定事件,因为您的输入字段将动态地重新创建。
这将适用于所有浏览器
我在stackoverflow答案上找到了这个解决方案
更多信息
查看我的更新
注意:现在已从jQuery的更高版本中删除。请使用而不是live。根据dknaack答案,线索是使用jquery live绑定更改事件,并在提交后重置输入字段: 必须在提交事件完成后执行重置。当提交是异步的时,例如在ajax成功事件中重置字段
这可能会有帮助!尝试使用live-$'.attachmentsUpload输入.file'.live'change',函数{$'form'.submit;}@杰森:不幸的是,这并没有改变你现在应该使用的jQuery 1.7+。在“改变”一词中,这对Chrome有帮助,但对IE没有帮助IE9@JarekWaliszko你是对的。我的答案已更新。@dknssck:谢谢您的努力,但出于某种原因,这在Chrome和Firefox中是有效的,但在IE IE9中不会向服务器提交文件,服务器端的ContentLength等于0。@JarekWaliszko我想这是因为ajax请求是异步的。因此,您可以尝试在重置变量之前将字段的值保存在变量中。然后提交你的变量。我的答案是updated请注意,从jQuery1.7开始,.live方法已被弃用,但可以改用.on或.delegate。有关更多信息,请参阅位于的jQuery文档。
$(".attachmentsUpload input.file").change(function () {
if ($(".attachmentsUpload input.file").val() == "") {
return;
}
// your ajax submit
$(".attachmentsUpload input.file").val("");
});
$(".attachmentsUpload input.file").live("change", function () {
if ($(".attachmentsUpload input.file").val() == "") {
return;
}
// get the inputs value
var fileInputContent = $(".attachmentsUpload input.file").val();
// your ajax submit
alert("submit value of the file input field=" + fileInputContent);
// reset the field
$(".attachmentsUpload input.file").replaceWith('<input type="file" class="file" name="file" />');
});
$(document).ready(function () {
$(".attachmentsUpload input.file").change(function () {
$('form').submit(); /* sync submit */
$(".attachmentsUpload input.file").replaceWith('<input type="file" class="file" name="file" />');
});
});
$(document).ready(function () {
$(".attachmentsUpload input.file").change(function () {
$('form').submit(); /* async submit */
});
});
.ajaxForm({
...
success: function (result) {
// reset the field - needed for IE to upload the same file second time
$this.find("input.file").replaceWith('<input type="file" class="file" name="file" />');
}
});