简体   繁体   中英

Drag and drop dynamically generated html element

I need to add a drag and drop function for my web application. The jquery-ui become my first choice to do so. I have read the tutorial in the jQuery-ui web site and start to programming. If i use the static elements in this file, this function work fine. But when i use ajax to generate element from database, these element cannot be drag and drop. I paste my code below:

<ul id="employee">
<li>
<h5>33333333</h5>
<img src='images/employee.png' width='96' height='96' />
</li>

<li>
<h5>33333333</h5>
<img src='images/employee.png' width='96' height='96' />
</li>

<li>
<h5>33333333</h5>
<img src='images/employee.png' width='96' height='96' />
</li>

<li>
<h5>33333333</h5>
<img src='images/employee.png' width='96' height='96' />
</li>
</ul>

$(document).ready(function() {
    $("#employee li").draggable();
});

These code work fine. I can drag the elements.

However, when i use the dynamically generated HTML element like below:

function loadEmployee() {
    $.getJSON("employee!find.action", function(data) {
        var showEmployee = $("#employee");
        showEmployee.html("");
        $.each(data.employeeList, function(i, employee) {
            newDiv = $("<li>");
            var div = "<h5>" + employee.number + "</h5>";
            div += "<img src='images/employee.png' width='96' height='96' //>"
            newDiv.html(div).appendTo(showEmployee);
        });
        showEmployee.show();
    });
}
$(document).ready(function() {
    loadEmployee();
    $("#employee li").draggable();
});

These code can show the employee information but the drag function doesn't work, how can i fix this problem? Thank you in advance!

jQuery is calling draggable() on the elements when the document is ready, just after the page loads. Any elements that match your query after that the page loads won't have draggable() applied to them by default.

The solution you outlined in your comment above (applying .draggable() to the newDiv) after it's created make sense to me.

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