gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:34:19 24 4
gpt4 key购买 nike

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

在 DOM 中,标签与“x”按钮一起生成。 'x' 按钮从 DOM 中删除元素,但从数组中删除时会出现问题。我能找到的最接近的解决方案是 this question ,但是我无法让它完全适合我。

Here's the codepen

这是 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
});

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

我也试过

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

类似的结果。

求助!提前致谢

最佳答案

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

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

Working demo

关于Javascript - 从动态创建的数组中删除特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25728715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com