javascript - IE11表单提交事件被调用,但是表单没有提交
问题描述
我有一个奇怪的问题,只发生在 IE11 上。我有以下表格:
<form id="myform" action="http://my.url.com/mypage" method="POST">
<a href="#" class="js-triggerFileInput">Send the file</a>
<input type="file" name="myfile" class="hidden js-inputFile" />
<input type="submit" value="submit" class="hidden" />
</form>
以及以下 javascript(带有转译器的 ES6):
class MyForm {
constructor() {
this.button = $('.js-triggerFileInput');
this.file = $('.js-inputFile');
this.form = $('#myform');
}
// when I click on the visible button, triggers the file input dialog box
this.button.click(() => {
this.file.click();
});
// the the file is selected in the dialog box, submit the form
this.file.change(() => {
this.form.submit();
});
// I added this just to debug
this.form.submit(() => {
console.log('submitted');
return true;
});
}
这适用于所有浏览器,除了 IE11,根本不提交表单。
我添加了一个调试来查看是否调用了提交事件,并且每次都被调用,但是浏览器不提交表单。
如果我尝试使用提交按钮提交表单,它可以正常工作,但是当我尝试使用 javascript 提交时,它会触发事件但不起作用。
有谁知道我的代码有问题?
我什至尝试了另一种方法:
<label for="myinput">Send the file</label>
<input id="myinput" type="file" class="hidden" />
并使用默认的标签/输入行为来触发输入文件,而不必使用.click()
它似乎工作得更好,但在 IE11 中,如果输入文件隐藏是不可见的(显示:无,可见性:隐藏或不透明度),这将不起作用: 0)。
Edit1:如果我通过浏览器控制台触发事件,则提交表单。
解决方案
我没有找到问题的根源,但是我找到了绕过这个 IE 错误的方法:
HTML:
<form id="myform" action="http://my.url.com/mypage" method="POST">
<label for="myfile">Send the file</label>
<input type="file" name="myfile" id="myfile" class="js-inputFile" />
<input type="submit" value="submit" class="hidden" />
</form>
JS:
class MyForm {
constructor() {
this.file = $('.js-inputFile');
this.form = $('#myform');
}
// the the file is selected in the dialog box, submit the form
this.file.change(() => {
this.form.submit();
});
}
如果我不使用 button + JS 来触发 input[type="file"] 行为,而是使用 label + id 来触发点击,它就像一个魅力。问题似乎与使用 JS 触发 input[type="file"] 有关。
还:
- 如果表单中没有 input[type="submit"] ,则 IE 不会发送表单。
- IE 不会触发 input[type="file"] is hidden 或 invisible,我使用 height: 0; 实现了相同的行为;宽度:0;