Javascript 如何使用可变参数删除Div?

Javascript 如何使用可变参数删除Div?,javascript,remove,Javascript,Remove,我正在尝试创建一种向我的表单添加条目的方法,以便用户可以选择他想要的条目数,但我无法让他删除: JavaScript var i = 1; var divContent = document.getElementById('formulario'); //Click to add a field function cria() { //This add a HTML Inputs and divs who the ID is variable h

我正在尝试创建一种向我的表单添加条目的方法,以便用户可以选择他想要的条目数,但我无法让他删除: JavaScript

    var i = 1;
    var divContent = document.getElementById('formulario');

    //Click to add a field
    function cria() {
        //This add a HTML Inputs and divs who the ID is variable how the 'i' is increasedf
        document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div><a href="#" data-id="1" onclick="remove(div'+i+',div2'+i+')" id="div'+i+'" id="adicionarCampo">- Remover campo</a>';
        i++;
    }
    function remove(div1, div2){
        var div = document.getElementById(div1);
        var div2 = document.getElementById(div2);
        div.remove();
        div2.remove();
        i--;
    }
var i=1;
var divContent=document.getElementById('formulario');
//单击以添加字段
函数cria(){
//这将添加一个HTML输入和divs谁的ID是变量“i”如何增加df
document.getElementById('formulario')。innerHTML+='NomeValor';
i++;
}
功能删除(第1部分,第2部分){
var div=document.getElementById(div1);
var div2=document.getElementById(div2);
div.remove();
div2.remove();
我--;
}
现在是HTML

           <form>
                <h4 class="card-tittle text-center">Taxas</h4>
                <div id="formulario" class="form row align-items-start">
                    <div class="mb-1 col-3" id="0">
                      <label for="nomeTx0" class="form-label">Nome</label>
                      <input type="text" class="form-control" id="nomeTx0" name="nomeTx0" required>
                    </div>
                    <div class="mb-1 col-3" id="0">
                      <label for="taxa0" class="form-label">Valor</label>
                      <input type="float" class="form-control" id="taxa0" name="taxa0" required>
                    </div>
                </div>
                    <a href="#" data-id="1" onclick="cria()" id="adicionarCampo">+ adicionar campo</a>
                <div class="mb-1 col-lg-12" style="text-align: center;">
                    <button class="btn btn-primary col-5" id="Enviar" type="submit" text="Enviar">Adicionar Taxas</button>
                </div>
            </form>

德克萨斯
诺姆
英勇
无柄分类群

ID=“taxa”+i但是当我调用remove()时;如果变量为空,则向我显示错误。

您希望将html元素的ID传递给函数remove,而不是传递其他内容

试试这个:

function remove(d1, d2){
        //what are passing to function...  id , or something else ?
        console.log(d1,d2);  
    
        // now I force the arguments passed to function to a valid value id for test

 
        var a = document.getElementById('div1'); // id is div1 
        var b = document.getElementById('div21'); // id is div21

        //Ask to parentNode to remove his child  
 
        a.parentNode.removeChild(a);   
        b.parentNode.removeChild(b);                   
        i--;
    }
首先,这确实不是正确的方法。 您的基本问题是依赖于
id
s来知道要添加和删除的元素,这导致您将
id
连接到动态创建的元素上,这些元素由长字符串和连接到其中的变量组成在现实中,您应该尽可能避免使用
id
s,因为它们会使您的代码非常脆弱,并且伸缩性不好。

这是HTML元素的完美用法。正如您从下面重新编写的代码中所看到的,所有
id
s都已删除--您不需要它们。此外,与将变量连接到其中的长字符串不同,只要在需要时复制/克隆模板即可。然后,您可以使用灵活组织的HTML在主包装器元素上只设置一个
单击
事件,在这里可以检查被单击的实际元素(the)。如果它是一个移除按钮,那么只需将整个包装器移除到单击的移除按钮即可

您现在可以添加和删除任意数量的项目,而无需
id
或计数变量

//获取对模板、外部div和添加“按钮”的引用
const template=document.querySelector(“模板”);
const wrapper=document.querySelector(“.wrapper”);
const add=document.querySelector(“.add”);
//在Javascript中设置add事件,而不是使用内联HTML
add.addEventListener(“单击”),函数(事件){
var clone=template.content.cloneNode(true);//克隆模板
appendChild(克隆);
});
//设置一个包装器级别的单击事件,其中的任何单击都将冒泡到该事件
addEventListener(“单击”),函数(事件){
//测试以查看是否单击了“删除”按钮
if(event.target.classList.contains(“删除”)){
//只需删除包含该特定组的最近的祖先div
//并将其移除。
event.target.closest(“div.templateWrapper”).remove();
}
});
.mb-1.col-lg-12{
文本对齐:居中;
}
.mb-1.col-3{
保证金:2倍;
}
。添加,。删除{
光标:指针;
颜色:蓝色;
}
.labelName{显示:内联块;宽度:3em;}
/*这只是为了更好地了解群体*/
.templateWrapper、.form{
背景色:aliceblue;
填充物:5px;
利润率:8px;
}

诺姆
英勇
-坎波酒店
德克萨斯
+阿迪西奥纳坎波酒店
诺姆
英勇
无柄分类群

代码中的问题是,您没有将字符串传递给remove函数,而是传递整个元素。这就是为什么document.getElementById找不到任何内容,因为它需要一个字符串作为参数。我对您的代码进行了一些重构,并且在删除字段时,链接-Remover campo保留了下来,没有被删除。通过将第三个参数传递给remove函数,我也解决了这个问题

    var i = 1;
var divContent = document.getElementById('formulario');

//Click to add a field
function cria() {
    //This add a HTML Inputs and divs who the ID is variable how the 'i' is increasedf
    document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div><a href="#" data-id="1" onclick="remove(`div'+i+'`, `div2'+i+'`, `div'+i+'remove`)" id="div'+i+'remove" id="adicionarCampo">- Remover campo</a>';
    i++;
}
function remove(div1, div2, link){
    var div = document.getElementById(div1);
    var div2 = document.getElementById(div2);
    var link = document.getElementById(link);
    divContent.removeChild(div);
    divContent.removeChild(div2);
    divContent.removeChild(link)
    i--;
}
var i=1;
var divContent=document.getElementById('formulario');
//单击以添加字段
函数cria(){
//这将添加一个HTML输入和divs谁的ID是变量“i”如何增加df
document.getElementById('formulario')。innerHTML+='NomeValor';
i++;
}
功能移除(第1部分、第2部分、链接){
var div=document.getElementById(div1);
var div2=document.getElementById(div2);
var link=document.getElementById(link);
divContent.removeChild(div);
divContent.removeChild(div2);
divContent.removeChild(链接)
我--;
}

代码运行的最简单方法是更改函数“cria”。(这不是最好的选择)

您错过了“”。 你有这个

onclick="remove(div'+i+',div2'+i+')"
你需要这个

onclick="remove(\'div'+i+'\',\'div2'+i+'\')"
Javascript只是不理解这些参数是字符串

以及更改后的全功能“cria”

function cria() {
    //This add a HTML Inputs and divs who the ID is variable how the 'i' is increasedf
    document.getElementById('formulario').innerHTML += '<div class="mb-1 col-3" id="div'+i+'"><label for="nomeTx0" class="form-label">Nome</label><input type="text" class="form-control" id="nomeTx'+i+'" name="nomeTx'+i+'" required></div><div class="mb-1 col-3" id="div2'+i+'"><label for="taxa'+i+'" class="form-label">Valor</label><input type="float" class="form-control" id="taxa'+i+'" name="taxa'+i+'" required></div><a href="#" data-id="1" onclick="remove(\'div'+i+'\',\'div2'+i+'\')" id="div'+i+'" id="adicionarCampo">- Remover campo</a>';
    i++;
}
函数cria(){
//这将添加一个HTML输入和divs谁的ID是变量“i”如何增加df
document.getElementById('formulario')。innerHTML+='NomeValor';
i++;
}

我唯一不完全同意的是您的“超链接用于导航”评论。锚不一定是超链接。开发人员在这里的意图是明确的:他们想要超链接的样式,而不是去任何地方,而是运行一些代码。就我个人而言,我不明白为什么在使用浏览器的原生“超链接”样式时,将通用元素的样式设置为超链接会被认为是“ok”