使用javascript动态删除表单中的元素

时间:2014-07-08 04:50:22

标签: javascript html5

我的html div部分是

<div id="upload">

<input type="button" id="add" value="Click here to add" onclick="uploadFile();">

<input type="hidden" name="fileCount" id="fileCount" value="0" />
</div>

我的javascript是

function uploadFile()
{
    var count = parseInt($('#fileCount').val(), 10);
    count = count + 1;
    if(count<=2){
        var x = document.createElement("INPUT");
        var br = document.createElement("br");
        var text = document.createElement("INPUT");
        var remove = document.createElement("INPUT");
        text.setAttribute("type", "text");
        text.setAttribute("name", "description_" + count);
        text.setAttribute("value", "file description");
        remove.setAttribute("type", "button");
        remove.setAttribute("value", "Delete");
        remove.setAttribute("id", "Delete"+count);
        remove.setAttribute("onclick", "remove();");

        x.setAttribute("type", "file");
        x.setAttribute("name", "file_" + count);
        x.setAttribute("id", "file_" + count);

        x.setAttribute("onchange","checkFile(this);");
        upload.appendChild(br);
        upload.appendChild(x);
        upload.appendChild(text);
        upload.appendChild(remove);
        $('#fileCount').val(count);
    }
    else{
        alert("cant upload more than two files");
    }
}

function remove()
{
    //  upload.getElementById(file_).remove();
}

当我动态点击Delete按钮时,我需要一个删除功能来删除相应的元素。

2 个答案:

答案 0 :(得分:0)

单击按钮调用此功能。

function removeDummy() { var elem = document.getElementById('elementtodelete'); elem.parentNode.removeChild(elem); return false; }

答案 1 :(得分:-1)

您可以使用jQuery remove()方法删除HTML和DOM中的元素。

$(selector).remove();

jQuery删除方法ref:remove()