从列表中删除元素-JQuery/JavaScript [英] Remove element from list - JQuery/JavaScript
问题描述
我在div中有一个这样的列表:
I have a list like this in a div:
<div id="x">5,2,3,1,4,9,8</div>
如何简单地从此列表中删除给定元素? 可以使用JQuery或JavaScript.
How do I simply remove a given element from this list? JQuery or JavaScript may be used.
请注意,列表中的数字是唯一的,并且它们是从int(11)类型的数据库中输入的,并非按任何顺序排列.
Please note that the numbers in the list are unique and they are coming in from a database of type int(11), they are not in any sort of order.
任何帮助表示赞赏的人...
Any help appreciated guys...
推荐答案
首先,获取文本:
var text=$("#x").text();
然后将其拆分:
var items=text.split(',');
如果没有项目,则将有一个空字符串作为数组的唯一元素.如果是这样,则清空数组:
If there's no items, you'll have an empty string as the only element of the array. If so, empty the array:
if(items.length==1&&items[0]=="") {
items=[];
}
现在将所有内容都转换为整数:(请注意,实际上并不需要此步骤,但是如果您要使用items
做其他事情,那么很高兴)
Now convert everything to an integer: (note that this step isn't actually required, but if you're doing anything else with items
, it's nice to have)
items=items.map(function(str) { return parseInt(str, 10); });
将要删除的项目放入变量:
Put the item you want to remove in a variable:
var itemToRemove=3;
在数组中查找:
var index=items.indexOf(itemToRemove);
如果找到它,则将其拼接出数组:
If it was found, splice it out of the array:
if(index!==-1) {
items.splice(index, 1);
}
将项目重新结合在一起:
Join the items back together:
text=items.join(',');
将其放回元素中
$("#x").text(text);
这篇关于从列表中删除元素-JQuery/JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!