简体   繁体   English

在追加元素的同时维护js

[英]Maintaining js while appending elements

I'm not super experienced and was hoping someone could give me some tips. 我不是很有经验,希望有人可以给我一些提示。

I'm trying to create a system where images can be transferred from a holding container to a manipulative container where they can be re-sized and dragged. 我正在尝试创建一个系统,在这个系统中,图像可以从一个容器转移到一个可以重新调整大小和拖动的操纵容器。

I have a manipulative here: Fiddle Demo 我在这里有一个操纵: 小提琴演示

And am trying to get the "click in/double-click out" system to work here: Fiddle Demo 我试图让“点击/双击”系统在这里工作: 小提琴演示

<div class="frame"></div>

<div class="inventory">
     <images>
</div>


$(".frame img")
    .draggable({
     containment: "parent",
    cursor: "move"
}).resizable({
    aspectRatio:1,
    containment: "parent",
    minHeight: 50,
    minWidth: 50
});


$('.inventory img').click(function(){ 
   $(this).appendTo(".frame");
 });
$('.frame img').dblclick(function(){
   $(this).appendTo(".inventory");
   $(this).removeClass('added');

});

The main problem I believe is that once I append the divs, the js doesn't refresh and apply based on the arrangements of elements. 我认为的主要问题是,一旦我附加了div,js就不会根据元素的排列进行刷新和应用。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Thank you! 谢谢!

Since the evaluation of the selectors need to be dynamic you need to use event delegation 由于选择器的评估需要是动态的,因此您需要使用事件委托

$('.inventory').on('click', 'img', function () {
    $(this).appendTo(".frame");
});
$('.frame').on('dblclick', 'img', function () {
    $(this).appendTo(".inventory");
    $(this).removeClass('added');
});

Demo: Fiddle 演示: 小提琴

Note: This will not handle the resizable/draggable behaviors - you will need to manually destroy/add this behaviors when you move the element from one container to another one 注意:这不会处理可调整大小/可拖动的行为 - 当您将元素从一个容器移动到另一个容器时,您将需要手动销毁/添加此行为

I updated Arun P Johny's fiddle: http://jsfiddle.net/u4xKW/2/ . 我更新了Arun P Johny的小提琴: http//jsfiddle.net/u4xKW/2/

$(".frame img")
    .draggable({
    containment: "parent",
    cursor: "move"
}).resizable({
    aspectRatio: 1,
    containment: "parent",
    minHeight: 50,
    minWidth: 50
});

$('.inventory').on('click', 'img', function () {
    $(this).resizable({
        aspectRatio: 1,
        containment: "parent",
        minHeight: 50,
        minWidth: 50
    });

    $(this).parent().appendTo(".frame").draggable({
        containment: "parent",
        cursor: "move"
    });
});

$('.frame').on('dblclick', '.ui-draggable', function () {
    $(this).appendTo(".inventory");
    $(this).draggable("destroy");
    $("img", this).resizable("destroy");
});

This adds and removes the draggable and resizable functions from the items when they are added and removed. 这会在添加和删除项目时添加和删除可拖动和可调整大小的功能。

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

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