使用Javascript - 从动态创建数组中删除特定元素 [英] Javascript - remove specific element from dynamically created array

查看:189
本文介绍了使用Javascript - 从动态创建数组中删除特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,用户可以创建标记(很像计算器这里),然后将其发送(POST)到后端被存储在数据库中。用户可以使标签,但也终于点击提交之前将其删除。

I have a page where users can create tags (much like here in stackoverflow), which are then sent(POST) to the back end to be stored in a database. The user can make tags but also remove them before finally hitting Submit.

在DOM与一个X按钮生成的标签一起。在X按钮将删除DOM元素,但麻烦的是来自阵列拆卸时。我能得到一个解决方案最接近的是这个问题的,但是我不能让它非常适合我的工作。

In the DOM the tags are generated along with an 'x' button. The 'x' button removes the element from the DOM, but the trouble comes when removing from the array. The closest I could get to a solution was this question, however I couldn't get it to quite work for me.

这里的codePEN

下面是JavaScript的(我使用jQuery)

Here's the javascript (i'm using 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
});

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

The end result is the splice takes out too many array items.

我也试过

tag_array.splice(tag_array.indexOf(tag),1);

到类似的结果。

请帮帮忙!在此先感谢

推荐答案

您可能已经应该使用类似 .indexOf水木清华()来gey ELEM的索引,然后拼接数组

You've probably should use smth like .indexOf() to gey an index of elem and then splice an array

tag_array.splice(tag_array.indexOf(elm),1);

工作演示

这篇关于使用Javascript - 从动态创建数组中删除特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆