[jquery]如何动态添加文件上传? [英] [jquery]How do I add file uploads dynamically?

查看:328
本文介绍了[jquery]如何动态添加文件上传?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传多个文件,所以我想通过jquery动态添加上传字段.现在,如果我有一个按钮,例如添加另一个字段",然后将新上传的文件追加到表单上,就可以执行此操作,但是我想做些不同.

I want to upload multiple files, so I want to add upload fields dynamically through jquery. Now I can do it if I have a button like "add another field", and append the new upload to the form, but I want to do it a bit differently.

最初,表单应该具有一个输入字段,在用户选择要上传的文件之后,我想立即添加另一个上传字段.有关如何执行此操作的任何想法?

Initially the form should have one input field, after the user selects a file to upload I want to immediately add another upload field. Any ideas on how to do this?

推荐答案

input元素具有change事件,该事件在表单字段更改时被触发.因此,您可以使用事件委托形式的on :

The input element has a change event that gets fired when the form field changes. So you can use the event-delegating form of on:

$('selector_for_your_form').on('change', 'input[type=file]', function() {
    var form = $(this).closest('form');
    form.append(/* ... markup for the new field ... */);
});

change事件实际上与表单挂钩,但是仅当事件通过与选择器input[type=file]匹配的元素传递时才触发处理程序. (jQuery确保change事件能够传播,即使在默认情况下也不会传播.)

The change event is actually hooked up to the form, but only fires the handler if the event passed through an element matching the selector input[type=file]. (jQuery ensures that the change event propagates, even in environments where it doesn't by default.)

实时示例:(我想您的标记会比那里的显示更有趣,并且看起来当然会更好)

jQuery(function($) {
  $('form').on('change', 'input[type=file]', function() {
    var form = $(this).closest('form');
    form.append('<input type="file">');
  });
});

  body {
    font-family: sans-serif;
  }
  p {
    margin: 0px;
  }

<form>
  <input type='file'>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

注意:

  • If you need to support obsolete versions of jQuery without on, you can use delegate which is like the delegating form of on but with the arguments in a different order.
  • If you need to support obsolete browsers and obsolete versions of jQuery, the change event may not bubble and older jQuery didn't make it bubble for delegate (even though it did when hooked directly).

无论哪种情况,请参见此答案的 2011年版本 (对JSBin链接进行了较小的更改)(例如)

In either case, see the 2011 version of this answer (with a minor change to the JSBin links) for examples, etc.

这篇关于[jquery]如何动态添加文件上传?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆