Javascript 作用域:删除在for循环(Js)中创建的元素

Javascript 作用域:删除在for循环(Js)中创建的元素,javascript,loops,scope,Javascript,Loops,Scope,一点背景信息: 旁边有按钮的输入框(删除每个按钮的按钮)是使用for循环创建的。(创建的数量取决于重新加载页面之前用户留在屏幕上的数量)。 显然,由于范围问题,“删除”按钮不起作用,因为它们是在循环中创建的 相关代码如下: for (var x = 0; x < currentTerms.length; x++){ amt++; } //This loop creates the necessarry amount of inputs needed, gi

一点背景信息:

旁边有按钮的输入框(删除每个按钮的按钮)是使用for循环创建的。(创建的数量取决于重新加载页面之前用户留在屏幕上的数量)。 显然,由于范围问题,“删除”按钮不起作用,因为它们是在循环中创建的

相关代码如下:

for (var x = 0; x < currentTerms.length; x++){
        amt++;
    }

    //This loop creates the necessarry amount of inputs needed, given the amount of stored
    //search terms:
    for (var f = 1; f < amt; f++){
        var id = idVal++;
        count++;
        //Create a div to hold the new input box &
        //the new "remove" button:
        var divv = document.createElement("div");
        divv.setAttribute("id", "div"+count);
        divv.setAttribute("class", "divvv");
        inputContainer.appendChild(divv);

        //Create the new input field, set the type, class & id.
        var newField = document.createElement("input");
        newField.setAttribute('type', 'text');
        newField.setAttribute('class', 'field');
        newField.setAttribute('id', "field"+id);
        divv.appendChild(newField);

        //The deleteCont div holds the remove button and it is 
        //added to the other div, now there is an input field
        //and another div inside the div:
        var deleteCont = document.createElement("div");
        var divId = "cont"+count;
        deleteCont.setAttribute("id", id);
        deleteCont.setAttribute("class", "remCont");
        divv.appendChild(deleteCont);

        //Finally, create the remove button itself and add it to the
        //container div that was created and place in the initial div:
        var remove = document.createElement("input");
        remove.setAttribute("type", "button");
        remove.setAttribute("value", "-");
        remove.setAttribute('class', 'remove');
        remove.setAttribute('id', "remove"+id);
        deleteCont.appendChild(remove);

        //When the user clicks the remove button with "-" value:
        remove.onclick = function () { 
            divv.parentNode.removeChild(divv);
            //Remove the error that may have been onscreen:
            document.getElementById("max").style.visibility="hidden";
            count--;
            toggleAddButton("show");
        };
    }
for(var x=0;x
在用户单击remove按钮时调用的函数中,您可以看到它当然不知道要删除哪个'divv'元素

据我所知,这可以很容易地用.nameIndex之类的东西来解决? 我只是不记得是怎么做的


任何指针都会大有帮助。

您忘记了每个DOM元素都是DOM树的一部分,并且完全了解其父元素和子元素。另外,像“onclick”这样的事件也知道事件发生在哪个元素上。您不必跟踪事件发生在“哪个”元素上,因为它实际上记录在事件中。从事件中,您可以轻松地在树中查找“向上”和“向下”以及“侧向”以查找您需要的任何内容。您可以使
onclick
方法本身作为参数传递吗?这使得范围变得明显(并且明确)。例如:
button onclick=“remove(this)”
将把
按钮
元素本身传递到
remove()
方法中,如果是这种情况,为什么上面的代码不起作用?在同一个页面上,它运行良好(没有for循环),这让我相信它是一个范围问题解决了:通过将要删除的div的id传递到onclick函数中并引用它,仍然删除了错误的项。