.change acting weird in IE9

2019-07-07 03:12发布

问题:

So I have a form submit set up like this

<button>edit a photo</button>
<form style="visibility: hidden;">
  <input type="file" id="file" name="file" val=""/>
  <input type="submit" name="submit">
</form>

and my javascript looks like this

$("#edit-button").click(function() {
  $("#file").click();
});

$("#file").change(function() {
  //submit form
});

At first I thought that perhaps IE9 wasn't recognizing the .change event from Jquery, however I noticed that if unhide my form and click it directly the change function is fired. If I use the edit button to activate the browse then the .change doesn't work even through it is changed.

I'm guess that when I click the "browse" button for the file input it doesn't get read the same as just $("#file").click(). Anyone know a way to remedy this?

回答1:

I'm guessing that is happening because your handlers are not being bound to the invisible form (this is the case, sometimes).

Try:

// document or some other container
$(document).on("change", "#file", function () {
    //submit form
});