为什么追加不可拖动的元素?

时间:2016-01-29 17:11:15

标签: javascript jquery

我使用“图像”类可拖动所有元素 然后我在页面上添加了更多“图像”元素 为什么附加元素不可拖动?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.12.0-beta.1/jquery-ui.min.js"></script>

<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">
<button class="button">Append image</button>
@echo off
setlocal EnableDelayedExpansion

set "last="
REM for every line do:
for /f "delims=" %%i in (test.log) do (
  REM does it contain "ERROR:"?
  echo %%i|find "ERROR:" >nul && (
    REM yes, then increase counter:
    set /a count+=1
   ) || ( 
    REM no, then print last "non ERROR" line and the counter:
    if !count! gtr 0 echo !last! ^(!count! Errors^)
    REM reset the counter for the next ERROR block:
    set count=0
    REM save last line:
    set "last=%%i"
  ) 
) 

View on JSFiddle

3 个答案:

答案 0 :(得分:3)

您需要在每次点击按钮时在新创建的图像上调用.draggable();

$(function(){

  $('.image').draggable(); //Draggable image (Jquery UI)

  $('.button').click(function(){     //append more image
    var img = $('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">');
    img.draggable();
    $('body').append(img);
  });

}) //End of script

小提琴:https://jsfiddle.net/0jxghvaa/2/

答案 1 :(得分:1)

您在加载时在draggable()元素上实例化.image插件。之后添加到DOM的任何元素都需要插件在创建后实例化它们。试试这个:

$('.image').draggable();

$('.button').click(function() {
    var $img = $('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">').appendTo('body');
    $img.draggable();
});

答案 2 :(得分:1)

新添加的元素不会自动拖动(只有那些最初存在的元素)。

在你的函数中,尝试重新声明该元素在创建后可以拖动:

$('.button').click(function(){
    $('body').append('<img class="image" src="http://nuclearpixel.com/content/icons/2010-02-09_stellar_icons_from_space_from_2005/earth_128.png">');
    $('.image').draggable();
});
相关问题