【问题标题】:How to get UL from [object HTMLUListElement] from cookie into Array?如何从 cookie 中的 [object HTMLUListElement] 获取 UL 到数组中?
【发布时间】:2016-05-02 18:16:22
【问题描述】:

如何从 cookie 中获取 [object HTMLUListElement] 的内容。 (内容为:

<ul id="checklist">
<li class="listItem" draggable="true">1</li>
<li class="listItem" draggable="true">2</li>
<li class="listItem" draggable="true">3</li>
<li class="listItem" draggable="true">4</li>
<li class="listItem" draggable="true">5</li>
<li class="listItem" draggable="true">6</li>
</ul>

如何从 [object HTMLUListElement] 中取回它并将其传递回 JavaScript 中的数组?

任何帮助或建议表示赞赏!

【问题讨论】:

标签: javascript arrays cookies html-lists


【解决方案1】:

我终于让 cookie 工作了。

问题在于 cookie 中的数据是 [object htmlulistelement] 作为字符串,而不是列表数据本身。

现在 ulCookie 中的数据是正确的,并且使用函数 getCookie(cname) (如http://www.w3schools.com/js/js_cookies.asp)可以正确检索数据。

如果存在 cookie,在加载 cookie 后添加 Eventlisteners 也很重要..

http://www.w3schools.com/js/js_cookies.asp 是一个有用的链接

查看这个 sn-p 以了解我的最终构建。 (我不得不分离js文件(cookies.js和main.js,我不知道如何在代码sn-p中实现这个,所以它可能在这里不起作用。我在js中评论了哪个文件开始的地方。)

最终工作的 readCookie 代码(cname 是 cookie 的名称):

function readCookie(document) {
  console.log(cname);
  function getCookie(cname) {
      var name = cname + "=";
      var ca = document.cookie.split(';');
      for (var i = 0; i < ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0) == ' ') {
              c = c.substring(1);
          }
          if (c.indexOf(name) == 0) {
              return c.substring(name.length, c.length);
          }
      }
      return "";
  }
  console.log(getCookie(cname));
};

整个代码如下:

// code by Friso NL - frisog at gmail .com

// events to create according ot: http://www.html5rocks.com/en/tutorials/dnd/basics/
//
// dragstart
// drag
// dragenter
// dragleave
// dragover
// drop
// dragend


// main.js //
window.onload = function() {

  window.parentOfItemslist = document.getElementById('checklist');
  // console.log(listItems);


  window.addEventListeners = function(listItems) {
    for (i = 0; i < listItems.length; i++) {
      window.listItem = listItems[i];


      listItem.setAttribute("order-id", i);



      listItem.addEventListener('dragstart', handleDragStart, false)
      listItem.addEventListener('dragenter', handleDragEnter, false)
      listItem.addEventListener('dragover', handleDragOver, false)
      listItem.addEventListener('dragleave', handleDragLeave, false)
      listItem.addEventListener('drop', handleDrop, false)
      listItem.addEventListener('dragend', handleDragEnd, false)
    }
  };




  window.listItems; // window.variable makes it global! instead of var = ...;

  window.createListInitial = function(e) {

    var listItmesWithoutExtra = document.querySelectorAll('.listItem');
    console.log(listItmesWithoutExtra);
    var extraLi = document.createElement("LI");

    extraLi.classList.add("ghostLi", "listItem");
    console.log(extraLi);
    var arrayListItmesWithoutExtra = Array.prototype.slice.call(listItmesWithoutExtra, 0);

    arrayListItmesWithoutExtra.push(extraLi);
    listItems = arrayListItmesWithoutExtra;

    console.log(listItems);
    window.parentOfItemslist = document.getElementById('checklist');
    console.log(parentOfItemslist);
    parentOfItemslist.innerHTML = "";
    for (i = 0; i < listItems.length; i++) {
      parentOfItemslist.appendChild(listItems[i]);
    }
    console.log(listItems);
    addEventListeners(listItems);
  };





  window.checkCurrentListItems = function(e) {
    var listItems = document.querySelectorAll('.listItem');
    return listItems;
  }

  var dragSrcEl = null;

  function handleDragStart(e) {
    this.className += " dragStartClass";
    dragSrcEl = this;

    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.innerHTML);
    // e.dataTransfer.setDragClass("dataTransferClass");

  }

  function handleDragOver(e) {
    // if (e.preventDefault) { not needed according to my question and anwers on : http://stackoverflow.com/questions/36920665/why-if-statement-with-e-preventdefault-drag-and-drop-javascript
    e.preventDefault();
    // }
    e.dataTransfer.dropEffect = 'move'; // sets cursor
    return false;

  }

  function handleDragEnter(e) {
    // this / e.target is the current hover target.
    this.classList.add('over');
  }

  function handleDragLeave(e) {
    this.classList.remove('over'); // this / e.target is previous target element.
  }

  window.handleDrop = function(e) {


    checkCurrentListItems();
    e.stopPropagation(); // stops the browser from redirecting.
    dragSrcOrderId = parseInt(dragSrcEl.getAttribute("order-id"));
    dragTargetOrderId = parseInt(this.getAttribute("order-id"));
    var tempThis = this;


    // Don't do anything if dropping the same column we're dragging.
    // and
    // check if only one difference and then do not execute
    // && ((Math.abs(dragSrcOrderId - dragTargetOrderId)) != 1)
    if (dragSrcEl != this) {
      // Set the source column's HTML to the HTML of the column we dropped on.
      var tempThis = this;

      function makeNewOrderIds(tempThis) {
        // check if up or down movement

        dragSrcEl.setAttribute("order-id", dragTargetOrderId);
        tempThis.setAttribute("order-id", dragTargetOrderId);

        //  find divs between old and new location and set new ids - different in up or down movement (if else)
        if (dragSrcOrderId < dragTargetOrderId) {
          for (i = dragSrcOrderId + 1; i < dragTargetOrderId; i++) {
            listItems[i].setAttribute("order-id", i - 1);
            // set new id src
            dragSrcEl.setAttribute("order-id", dragTargetOrderId - 1);
          }
        } else {
          for (i = dragTargetOrderId; i < dragSrcOrderId; i++) {
            listItems[i].setAttribute("order-id", i + 1);
            // set new id src
            dragSrcEl.setAttribute("order-id", dragTargetOrderId);

          }
        }

      };
      makeNewOrderIds(tempThis);


      dragSrcEl.classList.remove("dragStartClass");
      this.classList.remove('over'); // this / e.target is previous target element.
      reOrder(listItems);




    } else {

      dragSrcEl.classList.remove("dragStartClass");
      return false;

    }

  };

  function handleDragEnd(e) {

    for (i = 0; i < listItems.length; i++) {
      listItem = listItems[i];
      listItem.classList.remove('over');
    }
    dragSrcEl.classList.remove("dragStartClass");


  }



  window.reOrder = function(listItems) {


    var tempListItems = listItems;
    tempListItems = Array.prototype.slice.call(tempListItems, 0);

    tempListItems.sort(function(a, b) {
      return a.getAttribute("order-id") - b.getAttribute("order-id");
    });



    window.parentOfItemslist = document.getElementById('checklist');
    parentOfItemslist.innerHTML = "";

    for (var i = 0, l = tempListItems.length; i < l; i++) {
      parentOfItemslist.appendChild(tempListItems[i]);
    }

    createCookie(document);

  };

  CheckIfCookie(document);


};


// cookies.js //

window.cname = "ulCookie";
window.exdays = 20;

function CheckIfCookie(document) {


  if (document.cookie) {
    console.log("cookie!");

    readCookieAndSetLu(document);
    // read cookie


  } else {

    createListInitial();
    console.log(listItems);

  };
};

function createCookie(document) {
  // call this after drop and update of listItems
  window.cvalue = parentOfItemslist.innerHTML;

  function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
  }
  setCookie(cname, cvalue, exdays);


};

function readCookieAndSetLu(document) {
  console.log(cname);

  function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
      var c = ca[i];
      while (c.charAt(0) == ' ') {
        c = c.substring(1);
      }
      if (c.indexOf(name) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return "";
  }
  console.log(getCookie(cname));

  parentOfItemslist.innerHTML = getCookie(cname);

  newUl = document.getElementById('checklist');
  console.log(newUl);

  listItems = checkCurrentListItems();

  addEventListeners(listItems);


};
/* Prevent the text contents of draggable elements from being selectable. */

[draggable] {

  -moz-user-select: none;

  -khtml-user-select: none;

  -webkit-user-select: none;

  user-select: none;

  /* Required to make elements draggable in old WebKit */

  -khtml-user-drag: element;

  -webkit-user-drag: element;

}

.ghostLi {

  width: 20px;

  height: 20px;

  background-color: white !important;

}

.listItem {

  padding: 10px 10px 10px 10px;

  margin: 3px;

  background-color: red;

  color: white;

  width: 30px;

  border-top: thick solid white;

  border-top-width: 1px;

  -webkit-transition: all 0.2s ease-out;

  -moz-transition: all 0.2s ease-out;

  -ms-transition: all 0.2s ease-out;

  -o-transition: all 0.2s ease-out;

  transition: all 0.2s ease-out;

}

.dataTransferClass {

  background-color: brown;

}

.dragStartClass {

  opacity: 0;

  -webkit-transition: all 0.2s ease-out;

  -moz-transition: all 0.2s ease-out;

  -ms-transition: all 0.2s ease-out;

  -o-transition: all 0.2s ease-out;

  transition: all 0.2s ease-out;

}

.listItem.over {

  border-top: thick solid white;

  border-top-width: 50px;

  -webkit-transition: all 0.2s ease-out;

  -moz-transition: all 0.2s ease-out;

  -ms-transition: all 0.2s ease-out;

  -o-transition: all 0.2s ease-out;

  transition: all 0.2s ease-out;

}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="css/style.css" media="screen" title="no title" charset="utf-8">
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  <ul id="checklist">
    <li class="listItem" draggable="true">1</li>
    <li class="listItem" draggable="true">2</li>
    <li class="listItem" draggable="true">3</li>
    <li class="listItem" draggable="true">4</li>
    <li class="listItem" draggable="true">5</li>
    <li class="listItem" draggable="true">6</li>
  </ul>


</body>
<script type="text/javascript" src="app/js/main.js"></script>
<script type="text/javascript" src="app/js/cookies.js"></script>

</html>

【讨论】:

    【解决方案2】:

    你可以试试这个: 我假设您的 cookie 数据 HTMLUListElementcookObj 变量中。

    你可以写:

    var cookObj;
    for (var dVal in cookObj){
        console.log(dVal[member]);
    }
    

    并且,在检查元素的帮助下检查打印了哪些文本。


    函数 getCookie(名称)
    {
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    返回(值!= null)? unescape(值[1]) : null;
    }


    显示名为 UlCookie 的 cookie 的值:



    document.write(getCookie("UlCookie"));

    【讨论】:

    • 谢谢。不过,恐怕这个答案对我来说有点抽象。是不是通过 cookie 对象循环来获取单独的 LI?
    • 这是 cookie:ulCookie=[object HTMLUListElement];过期=格林威治标准时间 2016 年 5 月 22 日星期日 18:05:59; path=/learningJavascript002_todolist/;域=本地主机
    • 你能不能在将值通过 for in 循环后控制台显示给我。
    • 我不确定我是否做得对。但是如果我设置 member = 0 我得到: 0 main.js(第 66 行) 1 main.js(第 66 行) 2 main.js(第 66 行) 3 main.js(第 66 行) 4 main.js(第 66 行) 5 main.js(第 66 行) 6 main.js(第 66 行) 7 main.js(第 66 行) 8 main.js(第 66 行) 9 main.js(第 66 行) 10 1 main.js(第 66 行) 5 2
    • 所以基本上是很多数字而不是第一个 Li [0],这是我所希望的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2016-10-31
    • 1970-01-01
    • 2015-09-25
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多