簡體   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