Когда динамически добавленный div удаляется, последний созданный div следует за ним

У меня есть эта программа, которая может создавать перетаскиваемые элементы div. затем пользователь может поместить div в tds. Проблема, с которой я столкнулся, немного сбивает с толку, поэтому я привел пример, который, надеюсь, суммирует проблему.

Пример:

Допустим, вы делаете три div, когда я перетаскиваю div, который был сделан вторым, и опускаю его на td, ранее созданный div (в этом примере первый созданный div) оказывается рядом с удаленным div, и его текст также изменяется к div, который только что был удален.

Я не совсем уверен, почему это так, потому что все мои div имеют одинаковый идентификатор #temp? Если это слишком запутанно, пожалуйста, дайте мне знать.

Фотографии проблемы:

  1. Создайте 3 divs.

  2. Перетащите 2-й div на td и бросьте его.

  3. div, который был сделан ранее, следует за ним, и его текст меняется на тот, который был вставлен в td.

Вот полная версия моего кода:

var text;
var selectedText;
var inputBox = document.getElementById("input");

function showInputBox(){
   inputBox.style.display = "block";
}

function addElement() { 
 text = document.getElementById("input").value;

  // create a new div element and give it a unique id
  var newDiv = document.createElement("div");
  newDiv.id = 'temp'

  // and give it some content
  var newContent = document.createTextNode(text); 
  
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 

  $(function() {
    

    $("div").draggable({
     drag: function (e) {
         selectedText = event.target;
         text = $(selectedText).html();     
    }
    });
    $("#temp").draggable({
      drag: function (e) {
         selectedText = event.target;
         text = $(selectedText).html();
    }
    });



    $("td").droppable({
      drop: function( event, ui ) { 
        var selectedDiv = event.target;
          $( this )
          .addClass("div")
            .html(text);
              $("div").draggable();

          $( "#temp" ).remove();
      }
    });
  });
  document.getElementById("input").value = " ";
}

function addRedElement() { 
 text = document.getElementById("input").value;

  // create a new div element and give it a unique id
  var newDiv = document.createElement("div");
  newDiv.style.backgroundColor = "red";
  newDiv.id = 'temp'

  // and give it some content
  var newContent = document.createTextNode(text); 
  
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 

  $(function() {
    

    $("div").draggable({
     drag: function (e) {
         console.info('being dragged');
         selectedText = event.target;
         text = $(selectedText).html();
         console.info(text);
    }
    });
    $("#temp").draggable({
      drag: function (e) {
         console.info('being dragged');
         selectedText = event.target;
         text = $(selectedText).html();
         console.info(text);
    }
    });



    $("td").droppable({
      drop: function( event, ui ) { 
        var selectedDiv = event.target;
          $( this )
          .addClass("div")
            .html(text);
              $("div").draggable();

          $( "#temp" ).remove();
      }
    });
  });
  document.getElementById("input").value = " ";
}
body{
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

div {
  text-align: center;
  border: 1px solid #d3d3d3;
  width: 100px;
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}

.blank {

}

.div3 {
  position: absolute;
  text-align: center;
  border: 1px solid #d3d3d3;
  padding: 10px;
  cursor: move;
  z-index: 10;
  height: 20px ;
  background-color: white;
  width: 20px;
  color: #fff;
}


.div {
  text-align: center;
  padding: 10px;
  cursor: move;
  background-color: #2196F3;
  color: #fff;
}

td{
  border: 1px solid #d3d3d3;
  padding: 10px;
  height: 20px ;
  width: 200px;
}

div:hover {
  background-color: yellow;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <meta name = "viewport" content = "width=device-width">
    <title>repl.it</title>
      <script src = "https://code.jquery.com/jquery-3.5.0.js"></script>
    <link href = "style.css" rel = "stylesheet" type = "text/css" />
      <link rel = "stylesheet" href = "//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel = "stylesheet" href = "/resources/demos/style.css">
  <script src = "https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src = "https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
  <body>
<h1>Input text:</h1>
<p>input text and it will become a draggable div. You can then drag it to one of the tds </p>
    <input id = "input" type = "text" value = "text">
    <button onclick = "addElement()" >input</button> 

    <p>Drag your outputs to the div:</p>

<table border = "1">
  <tr>
    <td height = "50" width=100></td>
    <td height = "50" width=100></td>
    <td height = "50" width=100></td>
  </tr>
</table>


     <script src = "script.js"></script>
  </body>

</html>

🤔 А знаете ли вы, что...
JavaScript является одним из трех основных языков веб-разработки, вместе с HTML и CSS.


2
65
1

Ответ:

Решено

это потому, что все мои div имеют одинаковый идентификатор #temp?

Да!

У вас даже был этот комментарий в нужном месте! // create a new div element and give it a unique id

Это именно проблема. id должен быть уникальным. Поскольку это не так, когда вы нацеливаетесь на #temp, он всегда нацелен на первую страницу.

Итак, вам нужны уникальные идентификаторы... Ниже я просто использовал переменную elementCounter, установленную на ноль. Каждый раз, когда вы создаете div, он используется как часть id, а затем увеличивается.

Теперь в функции перетаскивания я использовал переменную currentlyDragged для хранения идентификатора удаляемого элемента в функции перетаскивания. Обратите внимание, что я использовал селектор атрибутов для нацеливания на элементы div, начинающиеся с «temp», и установил функцию перетаскивания.

И это работает.

var text;
var selectedText;
var inputBox = document.getElementById("input");

function showInputBox(){
   inputBox.style.display = "block";
}

var elementCounter = 0;
function addElement() { 
 text = document.getElementById("input").value;

  // create a new div element and give it a unique id
  var newDiv = document.createElement("div");
  newDiv.id = 'temp'+elementCounter;
  elementCounter++

  // and give it some content
  var newContent = document.createTextNode(text); 
  
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 

  $(function() {
    
    var currentlyDragged;
 
    /*$("div").draggable({
     drag: function (e) {
         currentlyDragged = e.target.id
         selectedText = event.target;
         text = $(selectedText).html();     
    }
    });*/
    $("[id^='temp']").draggable({
      drag: function (e) {
         currentlyDragged = e.target.id
         selectedText = event.target;
         text = $(selectedText).html();
    }
    });



    $("td").droppable({
      drop: function( event, ui ) { 
        var selectedDiv = event.target;
          $( this )
          .addClass("div")
            .html(text);
              $("div").draggable();

          $( "#"+currentlyDragged ).remove();
      }
    });
  });
  document.getElementById("input").value = " ";
}

function addRedElement() { 
 text = document.getElementById("input").value;

  // create a new div element and give it a unique id
  var newDiv = document.createElement("div");
  newDiv.style.backgroundColor = "red";
  newDiv.id = 'temp'

  // and give it some content
  var newContent = document.createTextNode(text); 
  
  // add the text node to the newly created div
  newDiv.appendChild(newContent);  

  // add the newly created element and its content into the DOM
  var currentDiv = document.getElementById("div1"); 
  document.body.insertBefore(newDiv, currentDiv); 

  $(function() {
    

    $("div").draggable({
     drag: function (e) {
         console.info('being dragged');
         selectedText = event.target;
         text = $(selectedText).html();
         console.info(text);
    }
    });
    $("#temp").draggable({
      drag: function (e) {
         console.info('being dragged');
         selectedText = event.target;
         text = $(selectedText).html();
         console.info(text);
    }
    });



    $("td").droppable({
      drop: function( event, ui ) { 
        var selectedDiv = event.target;
          $( this )
          .addClass("div")
            .html(text);
              $("div").draggable();

          $( "#temp" ).remove();
      }
    });
  });
  document.getElementById("input").value = " ";
}
body{
  font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

div {
  text-align: center;
  border: 1px solid #d3d3d3;
  width: 100px;
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}

.blank {

}

.div3 {
  position: absolute;
  text-align: center;
  border: 1px solid #d3d3d3;
  padding: 10px;
  cursor: move;
  z-index: 10;
  height: 20px ;
  background-color: white;
  width: 20px;
  color: #fff;
}


.div {
  text-align: center;
  padding: 10px;
  cursor: move;
  background-color: #2196F3;
  color: #fff;
}

td{
  border: 1px solid #d3d3d3;
  padding: 10px;
  height: 20px ;
  width: 200px;
}

div:hover {
  background-color: yellow;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <meta name = "viewport" content = "width=device-width">
    <title>repl.it</title>
      <script src = "https://code.jquery.com/jquery-3.5.0.js"></script>
    <link href = "style.css" rel = "stylesheet" type = "text/css" />
      <link rel = "stylesheet" href = "//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel = "stylesheet" href = "/resources/demos/style.css">
  <script src = "https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src = "https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  </head>
  <body>
<h1>Input text:</h1>
<p>input text and it will become a draggable div. You can then drag it to one of the tds </p>
    <input id = "input" type = "text" value = "text">
    <button onclick = "addElement()" >input</button> 

    <p>Drag your outputs to the div:</p>

<table border = "1">
  <tr>
    <td height = "50" width=100></td>
    <td height = "50" width=100></td>
    <td height = "50" width=100></td>
  </tr>
</table>


     <script src = "script.js"></script>
  </body>

</html>