jQuery - 动态添加字段字段

时间:2010-12-02 05:47:07

标签: jquery

我试图实现我在网站上找到的一些代码,当你点击一个href链接复制一个文件字段时,代码几乎与网站完全相同,但它根本不起作用。

有人可以看看,让我知道我哪里出错。

完整的代码如下:

的JavaScript

<script>
$(
function(){
    var jAddNewUpload = $( "#add-file-upload" );

    jAddNewUpload
        .attr( "href", "javascript:void( 0 )" )
        .click(
            function( objEvent ){
                AddNewUpload();

                objEvent.preventDefault();
                return( false );
            }
        );
}
);

function AddNewUpload(){
    var jFilesContainer = $( "mpfiles" );
    var jUploadTemplate = $( "#element-templates div.row" );
    var jUpload = jUploadTemplate.clone();
    var strNewHTML = jUpload.html();
    var intNewFileCount = (jFilesContainer.find( "div.row" ).length + 1);

    jUpload.attr( "id", ("file" + intNewFileCount) );

    strNewHTML = strNewHTML
        .replace(
            new RegExp( "::FIELD3::", "i" ), ("mpfile[]")
        );

    jUpload.html( strNewHTML );

    jFilesContainer.append( jUpload );
}
</script>

HTML

<div id="mpfiles">
    <div class="row">
        <label>Files:</label>
        <div class="files-box">
            <div class="file sub-file">
                <input class="file-input-area" name="mpfile[]" type="file" size="32" value="" />
                <input readonly="readonly" class="text" type="text" value="click to upload" />
                <a href="#" class="button">view</a>
            </div>
        </div>
    </div>
</div>

<div id="element-templates" style="display: none;">
    <div class="row">
        <label>Files:</label>
        <div class="files-box">
            <div class="file sub-file">
                <input class="file-input-area" type="file" name="::FIELD3::" size="32" value="" />
                <input readonly="readonly" class="text" type="text" value="click to upload" />
                <a href="#" class="button">view</a>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <label>&nbsp;</label>
    <a href="" id="add-file-upload">Upload another file</a>
</div>

我从中获取代码的网站是http://www.bennadel.com/blog/1375-Ask-Ben-Dynamically-Adding-File-Upload-Fields-To-A-Form-Using-jQuery.htm

1 个答案:

答案 0 :(得分:2)

function AddNewUpload(){ var jFilesContainer = $( "mpfiles" );

#之前需要mpfiles ...就像这样:

function AddNewUpload(){ var jFilesContainer = $( "#mpfiles" );