两次调用event.dataTransfer.setData不起作用

时间:2018-10-15 13:44:04

标签: javascript html

我正在尝试创建一个交换列表,以交换两个li元素。 调用event.dataTransfer.setData可以在第一次运行时运行,但是在第二次运行时则什么都不做。

我不确定为什么无法再次发送数据。 getData返回发送的第一个数据。

index.html

<!DOCTYPE html>
<html lang="en-US">
<head>
  <script src="actions.js"> </script>
</head>
<body>
  <div id="myDIV" class="header">
    <h2>My To Do List</h2>
    <input id="myInput" type="text" placeholder="Title...">
    <span id = "addButton" class="addBtn">Add</span>
  </div>

  <ul id="myUL">
    <li draggable="true">How</li>
    <li draggable="true">Are</li>
    <li draggable="true">You</li>
    <li draggable="true">Today</li>
    <li draggable="true">Good?</li>
  </ul>
</body>
</html>

actions.js

window.onload = function() {
  // fired on an element when a drag is started
  var ul = document.getElementById("myUL");
  ul.addEventListener("dragstart", function(event) {
    if(event.target.nodeName == "LI") {
      event.dataTransfer.setData("text/plain", event.target.innerHTML);
    }
  });

  ul.addEventListener("dragover", function(event) {
    if (event.preventDefault) {
      event.preventDefault();
    }
  });

  // fired on the element where the drop occured at the end of the drop operation
  ul.addEventListener("drop", function(event) {
    if(event.target.nodeName == "LI") {
      var caller = event.dataTransfer.getData("text/plain");
      event.dataTransfer.setData("text/plain", event.target.innerHTML);
      event.target.innerHTML = caller;
    }
  });

  // fired on the element where the drop occured at the end of the drop operation
  ul.addEventListener("dragend", function(event) {
    if(event.target.nodeName == "LI") {
      event.target.innerHTML = event.dataTransfer.getData("text/plain");
    }
  });
}

0 个答案:

没有答案