简体   繁体   English

动态添加的div不可拖动

[英]dynamically added div is not draggable

I'm trying to make my dynamically added divs draggable but if I call after 我正在尝试使可动态添加的div可拖动,但是如果我之后调用

$("#draggable").draggable({});

this 这个

for( var i = 0; i < 5; i++ ){
  var smallone = document.createElement('div');
  smallone.id = "draggable";
  smallone.className = "smallDiv";
  smallone.style.bacgroundColor = 'blue';

  document.body.appendChild(smallone);
}

there is no chance to make divs draggable. 没有使div可拖动的机会。
I know it works if i create divs first but I need to keep it like this because of my project and this example shows my problem. 我知道如果我首先创建divs就可以了,但是由于我的项目,我需要像这样保持它,并且此示例显示了我的问题。

Here is fiddle: http://jsfiddle.net/bimbochobot/9jstfwpm/4/ 这是小提琴: http : //jsfiddle.net/bimbochobot/9jstfwpm/4/

Thank you in advice. 谢谢你的指教。

You will have to initialize draggable widget after appending new element. 追加新元素后,您将必须initialize draggable小部件。

Try this fiddle : 试试这个小提琴

for( var i = 0; i < 5; i++ )
  {
      var smallone = document.createElement('div');
      smallone.id = "draggable";
      smallone.className = "smallDiv";
      smallone.style.backgroundColor = 'blue';
      document.body.appendChild(smallone);      
      $(smallone).draggable({});
   }

Use a class instead of id as id must be unique 使用类而不是id,因为id必须是唯一的

$(".draggable").draggable({});

Assign draggable class to all divs 将可拖动类分配给所有div

simple 1 ... 简单的1 ...

for( var i = 0; i < 5; i++ )
{
  var smallone = document.createElement('div');
  smallone.id = "draggable";
  smallone.className = "smallDiv";
  smallone.style.bacgroundColor = 'blue';

  document.body.appendChild(smallone);
  $(".smallDiv").draggable({});
}

it is working... http://jsfiddle.net/9jstfwpm/7/ 它正在工作... http://jsfiddle.net/9jstfwpm/7/

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

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