简体   繁体   中英

Appending/creating/removing items from a javascript array, ideas?

I have a requirement whereby I have two panes on a page, the pane on the left holds a series of records specific to a option selected from a drop down. Each record has a plus sign next to it, if this is pressed it will be 'moved' to the right hand pane and displayed under the option the user selected.

Multiple records can be put into each option selected.

I'm a bit unsure of the best approach to go with this. At first I was thinking about creating an array in Javascript and each click of plus would add the item to the array. When the form is ready to be submitted, use jQuery/Ajax to pass the array to a php function.

I suggest having this structure:

Options={
  'opt1':{},
  'opt2':{},
  'opt3':{}
}

and you have these records

//following is a structure view, not code
1: Record #1
2: Record #2
3: Record #3
4: Record #4

when user chooses to attach record#2 to opt3 , you do:

Options['opt3'][2]='Record #2';

New Options object: Options={ 'opt1':{}, 'opt2':{}, 'opt3':{ 2:'Record #2' } }

removing added options is as easy as:

delete Options['opt3'][2]

I've had to do similar things with arrays in javascript and I used the splice method

This is the definition:

The splice() method adds and/or removes elements to/from an array, and returns the removed element(s).

This is where I would start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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