jQuery UI-Sortable Cookie无效

时间:2014-05-30 13:25:29

标签: jquery jquery-ui cookies jquery-ui-sortable

working jsfiddle

我有两个容器。我想将元素从一个容器移动到另一个容器,并将带有新元素的附加容器保存到cookie

HTML

<div id="side">
    <div id="items1">item1</div>
    <div id="items2">item2</div>
    <div id="items3">item3</div>
    <div id="items4">item4</div>
    <div id="items5">item5</div>
    <div id="items6">item6</div>
</div>

<div id="external">
    <div id="items1">item1</div>
    <div id="items2">item2</div>
    <div id="items3">item3</div>
    <div id="items4">item4</div>
    <div id="items5">item5</div>
    <div id="items6">item6</div>
</div>

当我在 #side 中排序元素时,Cookie工作正常。

的jQuery

  var selector = "#side";
        var setCookieName = "listOrder";
        var setCookieExpiry = 7;
        function getOrder() {

        $.cookie(setCookieName, $(selector).sortable("toArray"), { expires: setCookieExpiry, path: "/" });
    }

    function restoreOrder() {
        var list = $(selector);
        if (list == null) return

        var cookie = $.cookie(setCookieName);

        var IDs = cookie.split(",");

        var items = list.sortable("toArray");

        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++) {

            var itemID = IDs[i];
            if (itemID in rebuild) {
                var item = rebuild[itemID];
                var child = $("div#side.ui-sortable").children("#" + item);
                var savedOrd = $("div#side.ui-sortable").children("#" + itemID);
                child.remove();
                $("div#side.ui-sortable").filter(":first").append(savedOrd);
            }
        }
    }

    $(document).ready(function() {
 $("#side, #external").sortable({ //source is my different container
                cursor: "move",
                connectWith: "#external",
                update: function() { getOrder(); }
            });
            restoreOrder();
        });

现在我可以将元素添加到我的主容器中,但刷新后我的新元素就会消失。

1 个答案:

答案 0 :(得分:0)

只需将您的Cookie渲染到#side div。

function restoreOrder() {
  var IDs = $.cookie(setCookieName).split(","),
    item, items = "";
  for (var i = 0, len = IDs.length; i < len; i++) {
    item = IDs[i];
    items += "<div id='" + item + "'>" + item + "</div>";
  }
  $("#side").html(items);
}