如何将EventListeners添加到已从LocalStorage更新的内容中



我正在使用Web应用程序,该应用程序允许DIV被拖放/重新排列。DIVS的新顺序存储在本地存储中,如果页面被刷新或从然后返回,然后将用户的选择订单从本地存储中获取并显示到页面。到目前为止,我的大多数事情都可以正常工作,但是当页面刷新/从返回到回到的页面时,DIVS将不再能够四处移动。在控制台中,事件听众似乎不再在可拖动目标上。我如何构建/编辑代码,以便即使用户刷新或在以后的时间点返回页面,也可以重新排列DIV?(我认为我目前正在处理活动的方式也不是很好,因此有关如何改进的建议。)

// get two groups of elements, those that are draggable and those that are drop targets
var draggable = document.querySelectorAll('[draggable]');
var targets = document.querySelectorAll('[data-drop-target]');
// div immediately surrounding bus routes
var busList = document.getElementById("bus-list");
var busListBuses = busList.children;
// make array from busListBuses which is an htmlCollection (not currently using this)
var divArr = Array.from(busListBuses);
// store the id of the draggable element when drag starts
function handleDragStart(e) {
  e.dataTransfer.setData("text", this.id); // sets 'text' value to equal the id of this
  this.classList.add("drag-start"); // class for styling the element being dragged 
}
function handleDragEnd(e) {
  e.target.classList.remove('drag-start');
}
function handleDragEnterLeave(e) {
  //
}
// handles dragover event (moving your source div over the target div element)
// If drop event occurs, the function retrieves the draggable element’s id from the DataTransfer object
function handleOverDrop(e) {
  e.preventDefault();
  var draggedId = e.dataTransfer.getData("text"); // retrieves drag data (DOMString) for specified type
  var draggedEl = document.getElementById(draggedId);
  draggedEl.parentNode.insertBefore(draggedEl, this); // inserts element being dragged into list
  var draggedArray = Array.from(draggedEl.parentNode.children); // creates new array which updates current location of each route
  if (e.type === "drop") {
    // when dropped, update localstorage
    savePage(draggedArray);
  }
}
// get each full bus-route div in #bus-list with p content as single arr item each
// called when item is dropped
function savePage(dArray) {
  // honestly i can't remember what this does precisely
  // but i can't seem to add to localstorage in the way i want without it
  var arr = Array.prototype.map.call(dArray, function(elem) {
    return elem.outerHTML;
  });
  localStorage.newList = JSON.stringify(arr); // have to stringify the array in order to add it to localstorage
}

// ideally it should just update the order of the bus routes to reflect local storage
// and add classes/ids to the divs etc. (hence using outerHTML)
function restorePage() {
  // getting the item from localstorage
  var getData = localStorage.getItem("newList");
  // parsing it back into an array
  var parsedData = JSON.parse(getData);
  // string to hold contents of array so they can be display via innerHTML
  var fullList = "";
  if (localStorage.getItem("newList") === null) {
    return; // maybe this is wrong but if there's nothing in local storage, don't do anything
  } else {
    for (let i = 0; i < parsedData.length; i++) {
      fullList = fullList + parsedData[i];
    }
    busList.innerHTML = fullList;
  }
}
// submit button to save changes to db

// probably better way to do this
for (let i = 0; i < draggable.length; i++) {
  draggable[i].addEventListener("dragstart", handleDragStart);
  draggable[i].addEventListener("dragend", handleDragEnd);
}
// drop target elements
for (let i = 0; i < targets.length; i++) {
  targets[i].addEventListener("dragover", handleOverDrop);
  targets[i].addEventListener("drop", handleOverDrop);
  targets[i].addEventListener("dragenter", handleDragEnterLeave);
  targets[i].addEventListener("dragleave", handleDragEnterLeave);
}
window.addEventListener('load', function(){
  restorePage();
});

我正在使用pug react,这是有帮助的哈巴狗文件。

html
  head
    title
    link(rel='stylesheet', type='text/css', href='stylesheets/normalize.css' )
    link(rel='stylesheet', type='text/css', href='stylesheets/style.css' )
  body
    div.container
      div#bus-list
        for route in routeInfo
          - var routeID = route.ID
          - var routePos = route.position
          div(class=route.type, draggable="true", data-drop-target="true", id=`r-${routePos}`).bus-route 
            p #{route.route} #{route.route_name}
      button(type="submit", value="submit") done!
  script(src='js/styling.js')

我认为问题在您的代码顺序中。JavaScript代码正在将其解析为脚本。因此,浏览器在脚本加载过程中执行命令。

如何工作:

  1. 浏览器加载没有任何项目的DOM
  2. 浏览器加载JS并将听众添加到元素(尚未加载)
  3. Brower发射onLoad(),您的脚本从存储中加载元素。
  4. 周期结束。

加载元素后,您需要添加侦听器。不是在那之前。

主题

您打一些重复的电话。

你做

var getData = localStorage.getItem("newList");
var parsedData = JSON.parse(getData);
var fullList = "";
if (localStorage.getItem("newList") === null) {
  return;
}

而不是

var getData = localStorage.getItem("newList");
if (getData === null) {
  return;
}
var parsedData = JSON.parse(getData);
var fullList = "";

它损害了可读性和性能。

我建议您阅读一些有关C语言和代码样式的书。这将帮助您旅途。

相关内容

  • 没有找到相关文章

最新更新