简体   繁体   中英

JQueryUI: Button inside a draggable div not working when div is dropped

First post on StackOverflow.

I tried to resume the issue in the title, and I made a jsfiddle here: http://jsfiddle.net/gBBcj/

The html generated seems correct, but the button in the dragged div does not work. I even tried to redefine it as a .button(), but with no success.

Thanks for your help!

$(".box").draggable({
    helper: 'clone'
});
$("#left").droppable({
    accept: '.box',
    drop: function (e, ui) {
        $(this).append('<div class="box"></div>');
        var droppedBox = $(this).children().last();
        $(droppedBox).html(ui.helper.html());
    }
});
$(".myButton").click(function () {
    alert("Clicked");
});

Use .on()

Read Event Delegation

Syntax

$( elements ).on( events, selector, data, handler );

$(".container").on('click', '.myButton', function () {
    alert("Clicked");
});

Fiddle Demo

The click() binding applies to the elements that exists at the time when you first attach it. It does not apply for the newly added elements.

Use on("click") method to attach the click event, as in Tushar Gupta's answer. It attaches a delegate to the container that will handle the "click" of the newly added elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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