我有一个使用jquery可以拖动的Div列表。
<div id="external-events">
<h4>List Of Staffs</h4>
<div class="external-event" data-id="1">Name</div> //Draggable
</div>
这是使其可拖动的代码
$('#external-events div.external-event').each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()),
id: $(this).data('id')
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
所以我必须实现它,以便Div是动态的,所以我添加了生成它的代码。它生成正确,但它没有获得jQuery属性,如可拖动。这是javascript代码:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Default.aspx/getListOfStaff",
data: {},
contentType: "application/json",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#external-events").html(msg.d);
}
});
/* initialize the external events
-----------------------------------------------------------------*/
$('#external-events div.external-event').each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()),
id: $(this).data('id')
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
我使用了firebug并检查了生成的html,它完全一样。有什么想法吗?
答案 0 :(得分:0)
这是因为默认情况下$ .ajax函数不是同步的。这意味着在$ .ajax调用之后,可能请求尚未完成,这意味着您的$("#external-events")
查询将返回0个元素。
试试这个:
$(document).ready(function () {
function makeDraggable() {
$('#external-events div.external-event').each(function () {
// create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
// it doesn't need to have a start or end
var eventObject = {
title: $.trim($(this).text()),
id: $(this).data('id')
};
// store the Event Object in the DOM element so we can get to it later
$(this).data('eventObject', eventObject);
// make the event draggable using jQuery UI
$(this).draggable({
zIndex: 999,
revert: true, // will cause the event to go back to its
revertDuration: 0 // original position after the drag
});
});
}
$.ajax({
type: "POST",
url: "Default.aspx/getListOfStaff",
data: {},
contentType: "application/json",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
$("#external-events").html(msg.d);
makeDraggable();
}
});
});