2013-09-28 66 views
1

我正在使用一个UI窗体(其中包括)允许用户点击一个链接来添加额外的文件上传输入字段,以防他希望上传超过标准3初始选项。用jquery添加额外的输入点击使用jquery

两件事情:

  1. 不禁想,一定有做什么,我试图做一个简单的方法。 JavaScript从来不是我强大的西装之一,我可能会走很长的路。
  2. 出于某种原因,我提出了解决方案;只允许添加一个附加字段,并且不再需要,它只是停止工作!我希望每次单击链接时都会添加另一个字段;不只是一次。

下面我一直在使用的代码;我留下了评论,所以你可以看到我已经尝试过。

的jQuery:

// add and remove addtional image upload inputs 
    jQuery('#add_image_upload_field').click(function(e) { 

    e.preventDefault(); 

    var newInput = '<input type="file" class="fullwidth" name="upload_attachment[]" />'; 

    // jQuery(this).prev().append(newInput).slideDown('slow'); 
    // jQuery('#upload_image input').filter(':last').append(newInput).slideDown('slow'); 
    // jQuery('input[name="upload_attachment[]"]').filter(':last').append('newInput'); 
    // jQuery('input[name="upload_attachment[]"]').append('newInput'); 

var addLink = '<a href="#" id="add_image_upload_field">Add another image input field</a>'; 

jQuery(this).parent().append(newInput); 
jQuery(this).remove(); 
jQuery('#upload_image').append(addLink); 

}); 

HTML:

<!-- Upload a picture --> 
<fieldset name="upload_image" id="upload_image"> 
    <label for="upload_image">Upload pictures:</label> 
    <input type="file" id="" tabindex="" name="upload_attachment[]" class="fullwidth" /> 
    <input type="file" id="" tabindex="" name="upload_attachment[]" class="fullwidth" /> 
    <input type="file" id="" tabindex="" name="upload_attachment[]" class="fullwidth" /> 

    <a href="#" id="add_image_upload_field">Add another image input field</a> 
    <!--<input type="button" id="add_image_upload_field" value="Add another image input field" />--> 

</fieldset> 

我已经看到了这个做了几十页,但就是不能让它开始工作;任何帮助表示赞赏。

回答

2

当您替换/添加元素时,附加到它的事件将消失。因此,如果您要添加新图像并希望附加事件处理程序,则需要委托加载页面时已存在的元素。像:

jQuery(document).on('click','#add_image_upload_field', function(e) { 

演示here

+0

感谢@Sergio,我知道ID是唯一的,所以我没有加入他们我的想法是给具有索引后添加他们。你的第二点是有道理的,你是对的;我已经忘记了这一点。我一直在试图找到一个选择器,它允许我在最后一次输入之后但在添加它之前的链接之前引入'newInput',但正如你所看到的,我迄今为止还没有... –

+0

@RonaldDeRuiter,我删除了ID部分,我看起来太快了,你的新链接取代了旧链接,而不是双倍。所以我的回答现在更加正确:)是否按预期工作? – Sergio

+0

非常感谢,完美的作品,只是测试它。我决心不去睡觉,直到它完成了muito obrigado! :D –