简体   繁体   English

使用 JavaScript createElement() 方法在 keydown 上创建的元素不适用于 jQuery draggable() 方法

[英]Element created on keydown using JavaScript createElement() method won't work with the jQuery draggable() method

I'm working on a drag and drop project where items can be added to a work area and dragged to be positioned.我正在开发一个拖放项目,可以将项目添加到工作区并拖动以定位。 I am trying to use a key code to create multiple of the same kind of element, all of which can be dragged.我正在尝试使用一个关键代码来创建多个相同类型的元素,所有这些元素都可以拖动。 The jQuery function works as long as the draggable element is created when the page loads, but if it's created using a function, the draggable() method isn't working on it.只要在页面加载时创建了可拖动元素,jQuery function 就可以工作,但是如果它是使用 function 创建的,则该方法无法正常工作()。 Is there a way to get the function to recognize the element created with a function?有没有办法让 function 识别使用 function 创建的元素?

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Draggable Div Test</title>
  <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>
  <style>
    .test {
      width: 50px;
      height: 50px;
    }
  </style>
  
  </head>
<body>
  <div id="area" style="border: 1px solid black; width: 500px; height: 500px;"> </div>
  
  <script>
    var area = document.getElementById("area");
    function duplicate(e) {
      switch(e.keyCode) {
        case 49:
        var test = document.createElement("div");
        test.classList.add("test");
        test.classList.add("draggable");
        console.log(test.classList)
        test.style.backgroundColor = "blue";
        area.appendChild(test);

        break
      }
    }
    document.addEventListener("keydown", duplicate)

    $( function() {
      $( ".test" ).draggable();
    } );
  </script>

</body>
</html>

Thanks谢谢

jQuery draggable has a function called clone : jQuery 可拖动有一个 function 称为clone

 $(function() {
     i = 0

     $("#draggable").draggable({
         helper: 'clone',
         appendTo: "#droppable",
     });

    $("#droppable").droppable({
        accept: "#draggable",
    }); 

    i++;

    var $obj = ui.helper.clone().attr( 'data-name', 'newelementdropped' +i).draggable({
   stop : function (event, ui) {
    YOUR CODE
    });
}

See this answer: Jquery draggable(), clone() to append div...Pls Fiddle my jsfiddle看到这个答案: Jquery draggable(), clone() to append div ...请拨弄我的 jsfiddle

Just re-initalize the plugin after you insert the element.插入元素后只需重新初始化插件。

Something like:就像是:

$(".test").draggable("destroy").draggable();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM