Javascript - 从动态创建的数组中删除特定元素

bju*_*own 4 javascript arrays jquery dynamic splice

我有一个页面,用户可以在其中创建标签(很像 stackoverflow 中的此处),然后将其发送(POST)到后端以存储在数据库中。用户可以创建标签,也可以在最终点击“提交”之前删除它们。

在 DOM 中,标签是与“x”按钮一起生成的。“x”按钮从 DOM 中删除元素,但从数组中删除时会出现麻烦。我能找到的最接近的解决方案是这个问题,但是我无法让它对我很有用。

这是代码笔

这是 javascript (我正在使用 JQuery)

window.tag_array = [];

$( "#addtag" ).click(function() {

var tag = $("#input-tag").val();

//if tag is empty
if(!$('#input-tag').val()) {

    alert("can't be empty");

    } else {
        //put tag.val into an array         
        tag_array.push(tag);

        //add to DOM
        $( "#tagsbox" )
        .append( "<div class='displaytag'><i>"+tag+"</i><input type='hidden' class='tag' value="+tag+"><button onClick='return false;' class='removetag'>x</button></div>" );

        //reset value in text area to null
        $("#input-tag").val("");

        //remove tag onclick
        $('.removetag').click(function() {
            $(this).parent().remove(); //remove tag from DOM

            //splice from array
            tag_array.splice( this, 1 ); //<--HERE IS PROBLEM (i think)

        });


    } //end else

    alert(tag_array); //check array
});
Run Code Online (Sandbox Code Playgroud)

最终结果是拼接取出了太多的数组项。

我也尝试过

tag_array.splice(tag_array.indexOf(tag),1);
Run Code Online (Sandbox Code Playgroud)

得到类似的结果。

请帮忙!提前致谢

小智 5

您可能应该使用类似的方法.indexOf()来获取元素的索引,然后拼接数组:

tag_array.splice(tag_array.indexOf(elm),1);
Run Code Online (Sandbox Code Playgroud)

工作演示