最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript splice is removing everything but the element requested - Stack Overflow

programmeradmin1浏览0评论

I have a pretty simple script that takes content from an input box, makes an array out of it, removes a desired element, and spits back the text.

I'm trying to use "splice()" to remove the item but it removes everything BUT that one item:

var listOfTitles = $('.title-list').val();
var arrayOfTitles = listOfTitles.split(',');
var updatedTitles = arrayOfTitles.splice(2,1);
$('.title-list').val(updatedTitles.join());

for example if I have this:

test1,test2,test3,test4

I can turn it into an array. I want to removed "test3" and output "test1,test2,test4". The problem is, it's returning "test3" not removing it.

jsfiddle of what's happening: /

I have a pretty simple script that takes content from an input box, makes an array out of it, removes a desired element, and spits back the text.

I'm trying to use "splice()" to remove the item but it removes everything BUT that one item:

var listOfTitles = $('.title-list').val();
var arrayOfTitles = listOfTitles.split(',');
var updatedTitles = arrayOfTitles.splice(2,1);
$('.title-list').val(updatedTitles.join());

for example if I have this:

test1,test2,test3,test4

I can turn it into an array. I want to removed "test3" and output "test1,test2,test4". The problem is, it's returning "test3" not removing it.

jsfiddle of what's happening: http://jsfiddle/C95kN/

Share Improve this question asked Apr 10, 2013 at 17:59 dcp3450dcp3450 11.2k24 gold badges64 silver badges114 bronze badges 2
  • 2 Where do you use splice in that code? – Bergi Commented Apr 10, 2013 at 18:00
  • it was a typo, I edited the question and added a jsfiddle – dcp3450 Commented Apr 10, 2013 at 18:06
Add a ment  | 

2 Answers 2

Reset to default 4

Splice() modifies the array in place and returns an array with the elements you remove.

What you want is arrayOfTitles not updatedTitles

See working fiddle: http://jsfiddle/C95kN/1/

splice changes the passed array and returns the removed elements. Simply do

arrayOfTitles.splice(2,1);
$('.title-list').val(arrayOfTitles.join());

Note that I supposed the slice instead of splice was a typo.

发布评论

评论列表(0)

  1. 暂无评论