jQuery UI sortable: determining in what order the items are

后端 未结 5 917
深忆病人
深忆病人 2020-12-13 20:22

Here is an interesting use of JavaScript: reordering items with drag and drop. The implementation itself in my page works fine, but is there a way to determine in which orde

5条回答
  •  自闭症患者
    2020-12-13 20:51

    UPDATED 2012

    FULL WORKING DEMO & SOURCE


    get the index position of the elements try to read this:

    • Getting the position of the element in a list when it's drag/dropped (ui.sortable)

    COOKIE plugin for jquery:

    • http://plugins.jquery.com/project/cookie

    JQUERY:

     $(function() {
        //coockie name
         var LI_POSITION = 'li_position';
           $('ul#sortable').sortable({
             //observe the update event...
                update: function(event, ui) {
                  //create the array that hold the positions...
                  var order = []; 
                    //loop trought each li...
                   $('#sortable li').each( function(e) {
    
                   //add each li position to the array...     
                   // the +1 is for make it start from 1 instead of 0
                  order.push( $(this).attr('id')  + '=' + ( $(this).index() + 1 ) );
                  });
                  // join the array as single variable...
                  var positions = order.join(';')
                   //use the variable as you need!
                  alert( positions );
                 // $.cookie( LI_POSITION , positions , { expires: 10 });
                }
            });
         });​
    

    HTML:

    • Item 1
    • Item 2
    • Item 3
    • Item 4
    • Item 5

    PHP:

    this is just an example but you got the idea: you may want use a database instead and use AJAX for get back the lis:

     $val ) {
    //explode each value found by "="...
    $pos = explode( '=' , $val );
    //format the result into li...
    $li .= '
  • '.$pos[1].'
  • '; } //display it echo $li; // use this for delete the cookie! // setcookie( 'li_position' , null ); } else { // no cookie available display default set of lis echo '
  • Fuji
  • Golden
  • Gala
  • William
  • Jordan
  • '; } ?>

提交回复
热议问题