make UI.sortable work with cookie plugin
I have actually found a snippet which works for one user, but however when I try to apply the code to my page, I can sort the elements but it never saves what I have sorted. Please tell me what is wrong with this code.
(I copied from another question, not mine)
var setSelector = "#sortable";
// set the cookie name
var setCookieName = "listOrder";
// set the cookie expiry time (days):
var setCookieExpiry = 7;
// function that writes the list order to a cookie
function getOrder() {
// save custom order to cookie
$.cookie(setCookieName, $(setSelector).sortable("toArray"), { expires: setCookieExpiry, path: "/" });
}
// function that restores the list order from a cookie
function restoreOrder() {
var list = $(setSelector);
if (list == null) return
// fetch the cookie value (saved order)
var cookie = $.cookie(setCookieName);
if (!cookie) return;
// make array from saved order
var IDs = cookie.split(",");
// fetch current order
var items = list.sortable("toArray");
// make array from current order
var rebuild = new Array();
for ( var v=0, len=items.length; v<len; v++ ){
rebuild[items[v]] = items[v];
}
for (var i = 0, n = IDs.length; i < n; i++) {
// item id from saved order
var itemID = IDs[i];
if (itemID in rebuild) {
// select item id from current order
var item = rebuild[i开发者_高级运维temID];
// select the item according to current order
var child = $("ul" + setSelector + ".ui-sortable").children("#" + item);
// select the item according to the saved order
var savedOrd = $("ul" + setSelector + ".ui-sortable").children("#" + itemID);
// remove all the items
child.remove();
// add the items in turn according to saved order
// we need to filter here since the "ui-sortable"
// class is applied to all ul elements and we
// only want the very first! You can modify this
// to support multiple lists - not tested!
$("ul" + setSelector + ".ui-sortable").filter(":first").append(savedOrd);
}
}
}
// here, we allow the user to sort the items
$(setSelector).sortable({
cursor: 'move',
items: 'li',
//axis: "y",
opacity: 0.6,
//revert: true,
scroll: true,
scrollSensitivity: 40,
placeholder: 'highlight',
update: function() { getOrder(); }
});
// here, we reload the saved order
restoreOrder();
It just does not save, i can sort and everything. this is my markup. i try to keep everything simple for test purpose.
<ul id="sortable">
<li>test 1</li>
<li>test 2</li>
</ul>
Please can you correct this code to make it save cookie and reload the saved settings when I refresh. I am so desperate for this one :))
Thank you!
You need to put ID to each <li>
for example:
<ul id="sortable">
<li id="item-1">test 1</li>
<li id="item-2">test 2</li>
</ul>
Also, make sure you close your code at the end with });
精彩评论