繁体   English   中英

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

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

我正在开发一个拖放项目,可以将项目添加到工作区并拖动以定位。 我正在尝试使用一个关键代码来创建多个相同类型的元素,所有这些元素都可以拖动。 只要在页面加载时创建了可拖动元素,jQuery function 就可以工作,但是如果它是使用 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>

谢谢

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
    });
}

看到这个答案: Jquery draggable(), clone() to append div ...请拨弄我的 jsfiddle

插入元素后只需重新初始化插件。

就像是:

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

暂无
暂无

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

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