2012-03-10 5 views
4

Я стараюсь, чтобы сохранить мой новый список в списке cookie, чтобы пользователь мог сортировать список, как они хотят. И в следующий раз, когда они откроют мой список страниц, это тот же порядок, что и при выходе из страницы. Это возможно?Сохранить новый список адресов

Я использую JQuery Mobile, и я делаю список сортируется таким образом:

$(document).ready(function() { 
    $('li').taphold(function() { 
     // the clicked LI 
     var clicked = $(this); 

     // all the LIs above the clicked one 
     var previousAll = clicked.prevAll(); 

     // only proceed if it's not already on top (no previous siblings) 
     if(previousAll.length > 0) { 
     // top LI 
     var top = $(previousAll[previousAll.length - 1]); 

     // immediately previous LI 
     var previous = $(previousAll[0]); 

     // how far up do we need to move the clicked LI? 
     var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop'); 

     // how far down do we need to move the previous siblings? 
     var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight()); 

     // let's move stuff 
     clicked.css('position', 'relative'); 
     previousAll.css('position', 'relative'); 
     clicked.animate({'top': -moveUp}); 
     previousAll.animate({'top': moveDown}, {complete: function() { 
      // rearrange the DOM and restore positioning when we're done moving 
      clicked.parent().prepend(clicked); 
      clicked.css({'position': 'static', 'top': 0}); 
      previousAll.css({'position': 'static', 'top': 0}); 
     }}); 
     } 
    }); 
    }); 

Когда пользователь нажмите и удерживайте Элемент списка, что пункт перейти к верхней части списка.

+ Моя страница также должна быть в автономном режиме.

UPDATE:

Как получить ссылки на новый список? Теперь у меня есть, как это:

JS

$('#home').live('pageinit', function(event) { 
    // Check if we have saved the list order 
    getListOrder(); 

    $('li').taphold(function() { 
     // the clicked LI 
     var clicked = $(this); 

     // all the LIs above the clicked one 
     var previousAll = clicked.prevAll(); 

     // only proceed if it's not already on top (no previous siblings) 
     if (previousAll.length > 0) { 
      // top LI 
      var top = $(previousAll[previousAll.length - 1]); 

      // immediately previous LI 
      var previous = $(previousAll[0]); 

      // how far up do we need to move the clicked LI? 
      var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop'); 

      // how far down do we need to move the previous siblings? 
      var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight()); 

      // let's move stuff 
      clicked.css('position', 'relative'); 
      previousAll.css('position', 'relative'); 
      clicked.animate({ 
       'top': -moveUp 
      }); 
      previousAll.animate({ 
       'top': moveDown 
      }, { 
       complete: function() { 
        // rearrange the DOM and restore positioning when we're done moving 
        clicked.parent().prepend(clicked); 
        clicked.css({ 
         'position': 'static', 
         'top': 0 
        }); 
        previousAll.css({ 
         'position': 'static', 
         'top': 0 
        }); 
        saveListOrder(); 
       } 
      }); 
     } 
    }); 

    $('#resetLO').click(function() { 
     resetListOrder(); 
    }); 

    $('#clearLS').click(function() { 
     clearLocalStorage(); 
    }); 
}); 

function saveListOrder() { 
    var $items = $('#theList li'); 

    $items.each(function(i) { 
     //alert('Order:' +$(this).attr('rel')+' I: '+i); // This is your rel value 
     // save the index and the value 
     localStorage.setItem(i, $(this).attr('rel')); 
    }); 
} 

function getListOrder() { 
    var list = $("#theList"); 
    var $items = $('#theList li'); 
    var item; 

    // check for localStorage 
    if(localStorage.getItem(0) == null) { 
     return; // use default list order 
    }   

    // remove the previous list 
    list.empty(); 

    $items.each(function(i) { 
     item = localStorage.getItem(i); 

     // create new list order 
     list.append('<li rel="'+item+'"><a href="#">List Item #'+item+'</a></li>'); 
    }); 
    list.listview('refresh');  
} 

function resetListOrder() { 
    var list = $("#theList"); 
    var $items = $('#theList li'); 
    var next; 

    // remove the previous list 
    list.empty(); 

    $items.each(function(i) { 
     next = i + 1; 
     list.append('<li rel="'+next+'"><a href="#">List Item #'+next+'</a></li>'); 
    }); 
    list.listview('refresh');  
} 

function clearLocalStorage() { 
    // remove all saved data 
    localStorage.clear();  
} 

HTML

<!DOCTYPE html> 
<html class="ui-mobile-rendering"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://jquerymobile.com/test/css/themes/default/jquery.mobile.css" /> 
    <script src="http://jquerymobile.com/test/js/jquery.js"></script> 
    <script src="http://jquerymobile.com/test/js/jquery.mobile.js"></script> 

</head> 
<body> 
<div data-role="page" id="home"> 
    <div data-role="content"> 

     <ul data-role="listview" data-theme="g" id="theList"> 
      <li rel="1"><a href="http://www.example1.com">List Item #1</a></li> 
      <li rel="2"><a href="http://www.example2.com">List Item #2</a></li> 
      <li rel="3"><a href="http://www.example3.com">List Item #3</a></li> 
      <li rel="4"><a href="http://www.example4.com">List Item #4</a></li> 
      <li rel="5"><a href="http://www.example5.com">List Item #5</a></li> 
      <li rel="6"><a href="http://www.example6.com">List Item #6</a></li> 
      <li rel="7"><a href="http://www.example7.com">List Item #7</a></li> 
      <li rel="8"><a href="http://www.example8.com">List Item #8</a></li> 
      <li rel="9"><a href="http://www.example9.com">List Item #9</a></li> 
      <li rel="10"><a href="http://www.example10.com">List Item #10</a></li> 
     </ul> 
     <br /> 
     <a href="#" data-role="button" id="resetLO">Reset List Order</a> 
     <a href="#" data-role="button" id="clearLS">Clear Local Storage</a> 
    </div> 
</div> 
</body> 
</html> 

И когда я изменить порядок списка и сохранить его, то изменить ссылку на "#" ,

Пример: Я двигаюсь Элемент3 в верхней части списка, чтобы изменить ссылку каждые пункты http://www.example3.com -> #

Так что я предполагаю, что это ясный старый список и сделать весь список снова. Поэтому, я думаю, мне нужно изменить эту линию, но я не знаю, как это сделать. list.append('<li rel="'+item+'"><a href="#">List Item #'+item+'</a></li>');

+0

Я сделал это один раз, и то, что я закончил, записывал содержимое и порядок списка в файл каждый раз, когда он менялся, а затем загружал этот файл при загрузке страницы. Будет ли это работать на вас? Кроме того, я уверен, что для этого есть плагин jQuery, поэтому вам не нужно делать это с помощью CSS ... – Colleen

+0

@Colleen: У вас есть примеры, чтобы дать мне? Я новичок в jQuery/HTML-кодировании :) – Eljas

ответ

2

Для HTML5 Я хотел бы посмотреть на LocalStorage

UPDATE:

Вот пример использования Local Storage

JS

$('#home').live('pageinit', function(event) { 
    // Check if we have saved the list order 
    getListOrder(); 

    $('li').taphold(function() { 
     // the clicked LI 
     var clicked = $(this); 

     // all the LIs above the clicked one 
     var previousAll = clicked.prevAll(); 

     // only proceed if it's not already on top (no previous siblings) 
     if (previousAll.length > 0) { 
      // top LI 
      var top = $(previousAll[previousAll.length - 1]); 

      // immediately previous LI 
      var previous = $(previousAll[0]); 

      // how far up do we need to move the clicked LI? 
      var moveUp = clicked.attr('offsetTop') - top.attr('offsetTop'); 

      // how far down do we need to move the previous siblings? 
      var moveDown = (clicked.offset().top + clicked.outerHeight()) - (previous.offset().top + previous.outerHeight()); 

      // let's move stuff 
      clicked.css('position', 'relative'); 
      previousAll.css('position', 'relative'); 
      clicked.animate({ 
       'top': -moveUp 
      }); 
      previousAll.animate({ 
       'top': moveDown 
      }, { 
       complete: function() { 
        // rearrange the DOM and restore positioning when we're done moving 
        clicked.parent().prepend(clicked); 
        clicked.css({ 
         'position': 'static', 
         'top': 0 
        }); 
        previousAll.css({ 
         'position': 'static', 
         'top': 0 
        }); 
        saveListOrder(); 
       } 
      }); 
     } 
    }); 

    $('#resetLO').click(function() { 
     resetListOrder(); 
    }); 

    $('#clearLS').click(function() { 
     clearLocalStorage(); 
    }); 
}); 

function saveListOrder() { 
    var $items = $('#theList li'); 

    $items.each(function(i) { 
     //alert('Order:' +$(this).attr('rel')+' I: '+i); // This is your rel value 
     // save the index and the value 
     localStorage.setItem(i, $(this).attr('rel')); 
    }); 
} 

function getListOrder() { 
    var list = $("#theList"); 
    var $items = $('#theList li'); 
    var item; 

    // check for localStorage 
    if(localStorage.getItem(0) == null) { 
     return; // use default list order 
    }   

    // remove the previous list 
    list.empty(); 

    $items.each(function(i) { 
     item = localStorage.getItem(i); 

     // create new list order 
     list.append('<li rel="'+item+'"><a href="#">List Item #'+item+'</a></li>'); 
    }); 
    list.listview('refresh');  
} 

function resetListOrder() { 
    var list = $("#theList"); 
    var $items = $('#theList li'); 
    var next; 

    // remove the previous list 
    list.empty(); 

    $items.each(function(i) { 
     next = i + 1; 
     list.append('<li rel="'+next+'"><a href="#">List Item #'+next+'</a></li>'); 
    }); 
    list.listview('refresh');  
} 

function clearLocalStorage() { 
    // remove all saved data 
    localStorage.clear();  
} 

HTML

<!DOCTYPE html> 
<html class="ui-mobile-rendering"> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://jquerymobile.com/test/css/themes/default/jquery.mobile.css" /> 
    <script src="http://jquerymobile.com/test/js/jquery.js"></script> 
    <script src="http://jquerymobile.com/test/js/jquery.mobile.js"></script> 

</head> 
<body> 
<div data-role="page" id="home"> 
    <div data-role="content"> 

     <ul data-role="listview" data-theme="g" id="theList"> 
      <li rel="1"><a href="#">List Item #1</a></li> 
      <li rel="2"><a href="#">List Item #2</a></li> 
      <li rel="3"><a href="#">List Item #3</a></li> 
      <li rel="4"><a href="#">List Item #4</a></li> 
      <li rel="5"><a href="#">List Item #5</a></li> 
      <li rel="6"><a href="#">List Item #6</a></li> 
      <li rel="7"><a href="#">List Item #7</a></li> 
      <li rel="8"><a href="#">List Item #8</a></li> 
      <li rel="9"><a href="#">List Item #9</a></li> 
      <li rel="10"><a href="#">List Item #10</a></li> 
     </ul> 
     <br /> 
     <a href="#" data-role="button" id="resetLO">Reset List Order</a> 
     <a href="#" data-role="button" id="clearLS">Clear Local Storage</a> 
    </div> 
</div> 
</body> 
</html> 
​ 
+0

Я не знаю, как использовать localStorage, потому что у меня есть около 10 элементов, которые уже есть в списке, и если пользователь сортирует их и сохраняет в localStorage, поэтому мне нужно как-то просто обновить это localStorage. Правильно? И как: D – Eljas

+0

Обновлено мой ответ –

+0

спасибо! именно то, что я искал! – Eljas

0

без демпинг 2 файлов целиком на вас, некоторые соответствующие выдержки из страницы I :

в моем файле JS:

//fetches the list and calls show list to show the contents 
function getList(){ 
    //alert("in getList"); 
    jQuery.ajax({ 
     url:"todolist.php", 
     success: function(responseText){showList(responseText)}, 
     error: ajaxFailure 
    }); 
} 
//keeps track of the new order when the user drags to reorder 
function updateOrder(){ 
    var listitems=document.getElementsByTagName("li"); 
    var liststring=""; 
    for(var i=0; i<listitems.length; i++){ 
     liststring=liststring+"\n"+listitems[i].firstChild.nodeValue; 
    } 
    jQuery.ajax({ 
     url:"todolist.php", 
     success: getList, 
     error: ajaxFailure, 
     type: "post", 
     data: {action: "set", items: liststring} 
    }); 
} 

ToDoList.PHP содержит (среди прочего контента):

} else { 
    $items=$_REQUEST["items"]; 
     if($action=="set"){ 
      file_put_contents("todolist.txt", $items); 
     } else { //add an item 
      print($items); 
      file_put_contents("todolist.txt", "\n".$items, FILE_APPEND); 
     } 
    } 
} else { 
    //print the current file 
    if(file_exists("todolist.txt")){ 
     $contents=file_get_contents("todolist.txt"); 
     if($contents!=""){ 
      $contents=trim($contents); 
      print($contents); 
     } 
    } 
} 

, и я только что назвал .sortable() в списке, чтобы сделать его dragable/Выбрасывается/сортировкой, если я правильно помню.

Однако метод php не учитывает вашу проблему использования в автономном режиме (если вы имеете в виду, что хотите сохранить полную функциональность), так как, конечно, запрос ajax требует, чтобы он был онлайн. Но я не уверен, сколько функций вам нужно, так что это может сработать для вас.

Смежные вопросы