【发布时间】:2015-12-29 03:15:46
【问题描述】:
我使用 jQuery 的 change 事件从我的计算机中捕获选择的图像。
$("#user_photo").change(function () {
alert('yes');
});
但我的问题是当我再次选择相同的文件时,此功能不起作用。是的,显然不会。但我想要一个解决方案。你能帮帮我吗?
【问题讨论】:
标签: jquery
我使用 jQuery 的 change 事件从我的计算机中捕获选择的图像。
$("#user_photo").change(function () {
alert('yes');
});
但我的问题是当我再次选择相同的文件时,此功能不起作用。是的,显然不会。但我想要一个解决方案。你能帮帮我吗?
【问题讨论】:
标签: jquery
这种行为在所有浏览器上并不相同。例如在firefox上使用以下代码sn-p,即使您选择相同的文件,您也会收到警报。
$('#test').on('change', function() {
alert('yes');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="file" />
但你可能会很棘手。您可以使用输入文件,当上传文件时,将其放在您的服务器上,销毁输入文件并重新创建一个新的输入文件。但是如果你想这样做,你必须决定如何在你的服务器上上传文件,因为不是每个浏览器都有 javascript FileAPI。这是一个例子:
$(document.body).on('change', '#test', function() {
// Upload the file on your servlet, i can't really do the code for that. You case use the FileAPI or a library for that. Just take care of browsers compatibility : http://caniuse.com/#feat=fileapi
// When the file is uploaded
alert('yes');
// Replace the input by a new one
$(this).replaceWith('<input id="test" type="file">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="file" />
当然,您可以通过显示上传的文件来改进此代码。
【讨论】:
在事件中使用,像这样
$("#user_photo").on("change", function () {
alert('yes');
});
或者如果元素是动态添加的,可以使用以下
$("body").on("change", "#user_photo", function () {
alert('yes');
});
【讨论】: