【问题标题】:Custom input:file - Prevent form submition under Firefox自定义输入:文件 - 防止在 Firefox 下提交表单
【发布时间】:2014-03-17 10:18:34
【问题描述】:

目标

我正在尝试创建/使用完全可定制的跨浏览器 CSS input:file。我隐藏了我的输入并将其包装在一个按钮中,以便能够在此按钮上应用 CSS:

$('button').on('click', function(event) {
    console.log('button.click');
    event.preventDefault();
    event.stopPropagation();
    $(this).find(':file').click();
    return false;
});
$(':file').click(function(event) {
    console.log('file.click');
    event.stopPropagation();
});
$(':file').change(function(event) {
    console.log('file.change');
    event.preventDefault();
    // ...
});
button {
	position: relative;
	overflow: hidden;
}
button > input[type=file] {
	position: absolute;
	top: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post">
    <button type="button">
        Import file
        <input type="file" name="file"/>
    </button>
</form>

(我添加了一些 jQuery 将这些元素链接在一起)

预期行为

在 Chrome 下,它可以正常工作:

  • button.clickfile.click 被触发
  • 我们选择我们的文件
  • file.change 被触发,我们可以进行自定义处理

问题

问题是 Firefox 在 button.click 之后重新加载页面,然后我们得到了这个序列:

  • button.clickfile.click被触发,并提交表单
  • 我们选择我们的文件
  • file.change 被触发,对于我们的旧 input:file(不再存在,因为页面已重新加载)
  • 未检测到新 file 的变化,我们无法进行治疗

我不确定是否像我想要的那样明确。在 Chrome 和 Firefox 下用调试工具运行 sn-p 看看有什么区别。

【问题讨论】:

    标签: jquery forms firefox submit


    【解决方案1】:

    您在type="button" 中缺少=,不是吗?添加它应该会有所帮助。

    【讨论】:

    • &lt;button&gt; 的默认 type 是“提交”,这就是它重新加载页面的原因
    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2015-08-20
    • 2016-05-11
    • 2017-09-15
    相关资源
    最近更新 更多