在以前的更改时附加新的文件上传按钮

Appending a new file upload button when the previous changes

本文关键字:文件 按钮      更新时间:2023-09-26

我有一个函数,当用户添加文件时,它使用 jQuery 添加额外的文件上传按钮。我的问题是我似乎无法以正确的格式添加它或每次都添加它。我当前的函数只是尝试直接添加字符串:

jQuery(document).ready(function($) {
    $(function() {
        $("input:file").change(function(){
            $("input:file").after("</td></tr><tr><td class='"field_name span4'"><strong></strong></td><td class='"field_option'"><input type='"file'" name='"pictures'">");
        });
    });
});

您可以在此处查看此内容的实时版本:http://1ro.co/salem/?module=insert

上面显示的方法的问题是它没有添加前两个结束标记:</td></tr>

我已经尝试过将$("input:file"(设置为变量等方法,但是它不会为第一个变量之后的每个值设置。例如:

var count = 0;
jQuery(document).ready(function($) {
    $(function() {
        var input = $("input:file");
        input.change(function(){
            input.after(input.get(count++));
        });
    });
});

但是这根本不会附加(理论上可能会附加每个元素(,并且我不能在input.get(count(上使用.after((。

简单来说,我希望改进这一点并使其附加一个新的文件上传按钮,并且格式不正确。如果可能的话,我宁愿使用方法 2,但目前我希望它正常工作。

您需要将

处理程序重新添加到每个新文件输入中,因此最好将其隔离在函数中:

var addfile = function() {
  var newRow = $("<tr><td class='"field_name span4'"><strong></strong></td>" +
      "<td class='"field_option'"><input type='"file'" name='"pictures'">").
    insertAfter($(this).closest('tr'));
  newRow.find('input:file').change(addfile);
};
$("input:file").change( addfile );

我刚刚尝试了您的现场演示,它正在插入一些内容。但它当然只发生一次,因为您的事件处理程序仅绑定到第一个对象。

我会使用如下所示的东西来尝试您的更改函数:

$('input:file').change(function() {
    $(this).closest('tr').after($(this).closest('tr').clone());
});

但是您的更改处理程序也必须重建。