动态删除后如何更改表单id

How to change form id after deleting dynamically?

本文关键字:表单 id 何更改 删除 动态      更新时间:2023-09-26

我在JavaScript中生成一个动态表单,当我通过id删除表单时,我不知道如何按顺序设置id 1,2,3…你可以在jsfiddle上查看我的代码

https://jsfiddle.net/wdLtv01x/1/

if (document.getElementById(childDiv))
{
    var child = document.getElementById(childDiv);
    child.parentNode.removeChild(child);
    i--;    
}

和抱歉我的英语不好。

谢谢。

通过在您的removeElement函数中添加i--;,我认为这工作得很好。

window.removeElement = function(parentDiv, childDiv){
    if (document.getElementById(childDiv)){
        var child = document.getElementById(childDiv);
        child.parentNode.removeChild(child);
        i--;
        //decrement();    
    }
};

注释后更新:

我为每个创建的表单添加了一个类,然后循环所有具有这个类的元素并更新表单编号。

var forms = document.getElementsByClassName('interview-form');
console.log(forms);
for(var j = 0; j < forms.length; j++){
    console.log(forms[j].getElementsByTagName('h2'));
    forms[j].getElementsByTagName('h2')[0].innerHTML = 'Interview '+ (j+2);
}

小提琴被更新了(但我只是为H2元素做了更新)。如果你有更多的问题,请留下评论。

参见更新后的fiddle

由于您在小提琴上添加了jQuery,所以我使用jQuery,因为它更简洁。

首先,为了更容易选择,我将interview类添加到每个div中。然后,当你删除一个div,尝试保存被删除的div的索引。最后,递减所有div的值index>=被删除的索引。

window.removeElement = function(parentDiv, childDiv){
    if (document.getElementById(childDiv)){
        var child = document.getElementById(childDiv);
        child.parentNode.removeChild(child);
        //save the index of removed element
        var removed_index = Number(childDiv.split("_")[1]);
        //add class interview to all divs
        $(".interview").each(function(index){
            if(index + 1 >= removed_index){
                //if true, change the title and id
                $(this).find("h2").text("Interview "+(index+1));
                $(this).attr("id", "id_"+(index + 1));
                $(this).find("button").attr("onclick", "removeElement('myCandidat','id_"+(index + 1)+"')");
            }
        });
        i--;
        //decrement();    
    }
};