简体   繁体   English

Jquery 从数组中删除元素

[英]Jquery remove element from array

This should be fun to solve:)解决这个问题应该很有趣:)

In a text field I have the value Apple,Peach,Banana .在文本字段中,我有值Apple,Peach,Banana

Using Jquery I created an array from that CSV.使用 Jquery,我从该 CSV 创建了一个数组。

In HTML I have a list of the fruits with a "remove" option next to each one.在 HTML 我有一个水果列表,每个水果旁边都有一个“删除”选项。 When I click "remove" I want to remove the corresponding fruit from the list and the text field.当我单击“删除”时,我想从列表和文本字段中删除相应的水果。

I'm missing one function that will remove fruits from the array.我缺少一个 function 将从阵列中删除水果。 What function should I use?我应该使用什么 function?

http://jsfiddle.net/BXWqK/19/ http://jsfiddle.net/BXWqK/19/

You should use JavaScript Splice您应该使用JavaScript 接头

fruits_array.splice(fruit_index,1);

You also need to change:您还需要更改:

$('#fruits').val(skills_array.join(',')); to $('#fruits').val(fruits_array.join(','));$('#fruits').val(fruits_array.join(','));

    var A=['Apple','Peach','Banana'];

    A.splice(1,1)

// removes 1 item starting at index[1] 
// returns ['Peach'];

The accepted solution is correct, but it doesn't mention that you shouldn't use indexOf to get the fruit_index to remove, because IndexOf not Supported in IE8 Browser接受的解决方案是正确的,但它没有提到您不应该使用 indexOf 来删除 fruit_index,因为IE8 浏览器不支持 IndexOf

You should use:你应该使用:

fruits_array.splice($.inArray('Peach', fruits_array), 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM