運氣很差。
在下面的代碼片段中,我首先嘗試阻止事件傳播,這樣它就不會上傳。
我有以下假設。
- 默認瀏覽器操作將在我的事件偵聽器被命中之前發生。
- 之后我可以再次發送事件。
<html>
<input id="file-input" type="file">
</html>
...
<script>
let ignoreEventForSecondTime = false
document.getElementById("file-input").addEventListener("click", (event) => {
if (!ignoreEventForSecondTime) {
event.stopImmediatePropagation() // Don't actually upload yet
const input = event.target
validate(input.files) // I only want this to run after users have picked the files
ignoreEventTheSecondTime = true // Don't run this block after I refire the event
input.dispatchEvent(event) // The intention is to let whatever event listener handle uploading the files afterwards.
} else {
ignoreEventTheSecondTime = false
}
}, { capturing: true })
</script>
uj5u.com熱心網友回復:
這似乎奏效了。問題是我不能只調度我停止傳播的同一個事件,以及從“單擊”處理程式更改為“更改”處理程式,以便在檔案對話框完成后查看檔案。
<html>
<input id="file-input" type="file">
</html>
...
<script>
let ignoreEventForSecondTime = false
document.getElementById("file-input").addEventListener("change", (event) => { // LINE CHANGED
if (!ignoreEventForSecondTime) {
event.stopImmediatePropagation() // Don't actually upload yet
const input = event.target
validate(input.files)
ignoreEventTheSecondTime = true // Don't run this block after I refire the event
input.dispatchEvent(new Event('change', event)) // LINE CHANGED
} else {
ignoreEventTheSecondTime = false
}
}, { capturing: true })
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/465569.html
標籤:javascript html dom 事件 浏览器
