简体   繁体   English

在 Edge 中触发单击文件输入时不会触发更改事件

[英]Change event isn't fired when triggering click on file input in Edge

I'm having issues with uploading a file in Edge.我在 Edge 中上传文件时遇到问题。 The way I am currently doing it works in both Chrome and Firefox but not in edge.我目前的做法在 Chrome 和 Firefox 中都适用,但在 Edge 中无效。

<div id="banner-message">
    <button id="UploadButton">Upload</button>
    <input type="file" id="testUploader" style="display: none;" />
</div>

<script type="text/javascript">
    $("#UploadButton").on("click", function () {
        $("#testUploader").trigger("click");

        $("#testUploader").on("change", function() {
            console.log("change");
        });
    });
</script>

When I click on the upload button I am able to select a file to upload but when I choose a file nothing happens.当我单击上传按钮时,我可以选择要上传的文件,但是当我选择文件时,什么也没有发生。 Whereas when I choose a file in Chrome or Firefox the change event is fired and logged in the console.而当我在 Chrome 或 Firefox 中选择一个文件时,更改事件会被触发并记录在控制台中。

Here is a working JSFiddle that shows the issue: https://jsfiddle.net/xpvt214o/34688/这是一个显示问题的有效 JSFiddle: https ://jsfiddle.net/xpvt214o/34688/

I was able to solve this.我能够解决这个问题。 I moved the change event to outside of the click event and all seems to be working now.我将change事件移到了click事件之外,现在似乎一切正常。 Not sure why this is only an issue in Edge though.不知道为什么这只是 Edge 中的一个问题。

Working:工作:

<script type="text/javascript">
    $("#UploadButton").on("click", function () {
        $("#testUploader").trigger("click");
    });

    $("#testUploader").on("change", function() {
        console.log("change");
    });
</script>

changed "change" to "click" and it is working.将“更改”更改为“单击”并且它正在工作。

<script type="text/javascript">
    $("#UploadButton").on("click", function () {
        $("#testUploader").trigger("click");

        $("#testUploader").on("click", function() {
            alert("change");
        });
    });
</script>

This problem occurs because event listener is added after triggering click event.出现这个问题是因为触发click事件后添加了事件监听器。 If you really need to add event listener in another listener you need to do it firstly and then trigger this event.如果您确实需要在另一个侦听器中添加事件侦听器,则需要先执行此操作,然后再触发此事件。 So try this:所以试试这个:

<script type="text/javascript">
    $("#UploadButton").on("click", function () {
        $("#testUploader").on("change", function() {
            console.log("change");
        });

        $("#testUploader").trigger("click");
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM