jquery - 文件类型的输入事件在 Safari 浏览器中未触发

标签 jquery safari

我正在使用 AJAX 和 jQuery 上传文件。它在 Chrome 和 Firefox 中运行良好,但我遇到的问题是在 Safari 中。我尝试对此进行调试,但当我上传文件时调试器没有停止。

<input type="file" class="file_input" name="myfile"/>
$(document).on('input', '.file_input', function() {
  var that = $(this);
  var formData = new FormData();
  formData.append("userfile", this.files[0]);
  showLoader();

  $.ajax({
    cache: false,
    headers: {
      'X-CSRF-Token': _token
    },
    url: base_url + "controller/action",
    type: 'POST',
    data: formData,
    contentType: false,
    processData: false,
    success: function(data) {
      that.closest('tr').find('.document').empty();
      hideLoader();
    }
  });
});

最佳答案

Safari 不支持 file 输入元素上的 input 事件:

(Safari and some other browsers) don't fire an input event when (un)checking a checkbox or radio button, or when changing the selected file(s) of an . See Chrome bug, WebKit bug, and Firefox bug

https://caniuse.com/#feat=input-event

要解决此问题,您可以使用更广泛支持的 change 事件:

$(document).on('change', '.file_input', function() {
  // your code...
});
<小时/>

- 2020 年更新 -

Safari 中的此问题已在 2020 年 3 月发布的 13.1 版本中得到修复。需要明确的是,此后的任何版本的 Safari 现在都支持 文件 上的 input 事件输入。

如果您需要支持旧版本的 Safari,那么您仍然需要使用 change 事件,如我上面的原始答案中所述。

关于jquery - 文件类型的输入事件在 Safari 浏览器中未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58341044/

相关文章:

javascript - Jquery .empty() 前 2 个元素

javascript - Safari 错误 kCFErrorDomainWinSock :10054

safari - 您可以使用 Safari 扩展中的 XmlHttpRequest 发送 cookie 吗?

javascript - 为什么 Angular 4 plunker 可在 Safari 上运行,但不能在 Chrome 上运行

jquery - Windows XP 上有多个版本的 Safari?

javascript - 如何在 ASP.NET 中使用 jQuery 来改变 'li' 的颜色?

javascript - 鼠标悬停在 div 网格上时随机颜色变化

jquery - 在 jQuery 中结合正则表达式

javascript - 带音频标签的 Safari 浏览器不起作用

javascript - 我可以使用 console/alert/some-other-means 一次读出所有 CSS 属性吗?