Is there a way to bind an event when a user selects a file to upload and clicks on "open", I want to trigger the event when the user has clicked on open.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
In that scenario, the change
event will be fired.
If you have this HTML:
<input type="file" id="fileInput" />
Then use this JS:
window.onload = function () {
document.getElementById("fileInput").onchange = function () {
// this.value
};
};
(with the option of using addEventListener
/attachEvent
instead of setting the onclick
property)
Inside the handler, you can use this.value
to get the file selected.
Of course, with jQuery, you can use:
$(document).ready(function () {
$("#fileInput").on("change", function () {
// this.value OR $(this).val()
});
});
NOTE: The window.onload
and $(document).ready
handlers are used to make sure the element is available. Of course, this event can occur much later than actually necessary, since they wait for all elements on the page to be ready (and window.onload
waits even longer for things like images to be loaded). An option is to bind the onchange
handler immediately after the element on the page or at the end of the <body>
.