Jquery把元素放在另一个里面

时间:2014-03-20 15:15:57

标签: javascript jquery html jquery-ui dom

我有一些图像和一些可以拖放图像的元素

<span name="imie" id="drag1" class="drag">
    <img name='aa' id='test' src="http://placehold.it/80x80/c9112d/fff&text=1" width="70px" height="20px" />
    </span>
    <span>Imię</span> 

<div class="col droppable">
    <div class="canvas">
        <img class="img-bg" src="test.jpg">
    </div>
    <div class="canvas">
        <img class="img-bg" src="test.jpg">
    </div>                    
</div>

我想在<div class="canvas">之后或之前在img内添加删除的框。我想看到那个盒子在img上,但是在代码中它应该在canvas里面而不是之后 这是我的剧本

 var counter = 0;
        var x = null;
        //Make element draggable
        $(".drag").draggable({
            helper: 'clone',
            cursor: 'move',
            tolerance: 'fit',
            revert: true
        });

        $(".droppable").droppable({
            accept: '.drag',
            activeClass: "drop-area",
            drop: function (e, ui) {
                if ($(ui.draggable)[0].id !== "") {


                    x = ui.helper.clone();
                    ui.helper.remove();
                    x.draggable({
                        helper: 'original',
                        cursor: 'move',
                        containment: '.droppable',
                        tolerance: 'fit',
                        drop: function (event, ui) {
                            $(ui.draggable).remove();
                        }
                    });


                    x.addClass('remove');

                    var el = $("<span><a href='Javascript:void(0)' class='xicon delete'                  title='Remove'</a>X</span>");
                    $(el).insertAfter($(x.find('img')));
                    x.appendTo('.droppable');
                    $('.delete').on('click', function () {
                        $(this).parent().parent('span').remove();
                    });
                    $('.delete').parent().parent('span').dblclick(function () {
                        $(this).remove();
                    });
                }
            }
        });

我认为问题出在x.appendTo('.droppable');。但我无法处理它。 整个例子在线HERE

2 个答案:

答案 0 :(得分:2)

您正在寻找append

$( ".canvas" ).append( "<p>whateva</p>" );

参考:https://api.jquery.com/append/

答案 1 :(得分:2)

您必须使<div class="canvas"></div>可放置而不是<div class="col droppable"></div>

尝试:

HTML:

<div class="col ">
    <div class="canvas droppable">
        <img class="img-bg" src="http://formularze.iform.pl/zdjecia/formularze/4556/SF_sdfra.gif">
    </div>
    <div class="canvas droppable">
        <img class="img-bg" src="http://formularze.iform.pl/zdjecia/formularze/4556/SF_sdfra.gif">
    </div>                    
</div>

JS:

$(this).append(x);

DEMO

或者如果你想在img尝试之前:

$(this).prepend(x);

DEMO2