简体   繁体   English

如何在动态创建的输入类型“文件”上触发点击事件?

[英]How do I trigger click event on dynamically created input type 'file'?

I am attempting to add an input of type 'file' to a form dynamically. 我正在尝试将“文件”类型的输入动态添加到表单。 Actually the end user can add as many files as they would like to a form, so an array concept is needed. 实际上,最终用户可以向表单添加任意数量的文件,因此需要一个数组概念。 I can inject dynamic elements, but I can't figure out how to dynamically invoke the click of the input element just injected. 我可以注入动态元素,但无法弄清楚如何动态调用刚刚注入的输入元素的点击。 Also, need to remove the dynamic element if the user chooses cancel on the input element. 另外,如果用户在输入元素上选择“取消”,则需要删除动态元素。

I have created a jsfiddle showing the injection but the click event never fires when the trigger is run. 我创建了一个显示注入的jsfiddle ,但是在运行触发器时click事件从不触发。

How do I trigger the 'click' event after injecting this element? 注入此元素后如何触发“点击”事件?

jsFiddle Html jsFiddle HTML

<input id='button1' type='button' value='button1'>
<div class='container'>

</div>

jsFiddle JavaScript jsFiddle JavaScript

$(document).ready(function () {
    $('#button1').on('click', function(event) {
    Button1_Click(event);
  });
});

function Button1_Click(event) {
    var container = $('.container');
  var containerChildren = $(container).children();
  var containerChildrenCount = $(containerChildren).length;
  var inputId = 'fileInput[' + containerChildrenCount + ']';
    $('.container').append('<input id="' + inputId + '" type="file" />');
  $('#' + inputId).trigger('click');
}

Try removing the [] from the inputId variable. 尝试从inputId变量中删除[]

I got it to work in your fiddle by changing it to this 通过将其更改为

var inputId = 'fileInput-' + containerChildrenCount

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM