jQuery拖放在Ajax上加载Div [英] Jquery Drag and Drop on Ajax loaded Div
问题描述
我希望能够将页面上的元素拖动到ajax加载的div内的可放置元素中.当我将droppable元素放置在常规页面中时,而在ajax加载的div中具有相同元素时,我可以使代码工作.我非常确定这是因为我调用脚本的方式以及它们在dom上的加载方式,但是我找不到解决方案.注意:我已经尝试在调用jquery ui之前调用加载ajax内容的代码,但这也不起作用. 这就是我的一切调用方式,为简洁起见,我删除了多余的代码.
I want to be able to drag an element on the page into a droppable element inside an ajax loaded div. I can get the code to work when I place the droppable element in the regular page but not when i have the same element on the ajax loaded div. Im pretty sure its because of the way I'm calling scripts and how they load on the dom, but I can't find the solution. Note: I have tried calling the code which loads the ajax content before calling jquery ui but that didn't work either. Here is how I'm calling everything, I removed the extraneous code for brevity.
主页
<head>
<scripts -- jquery, jquery ui>
<script>
$(document).ready(function(){
$( "#site-preview" ).load( "/site/preview" );
});
</script>
</head>
<body>
<div class="draggable><img src=//etc/> </div>
//if I put this div here, I can drop to it, so i know the drop code works.
// <div class="droppable col-md-2" style="height:100px;border:1px solid gray"><p> </p></div>
<div id="site-preview"></div>
<script>
$(function() {
$( ".draggable" ).draggable({
helper:'clone',
appendTo: 'body',
scroll: false
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" ).find( "p" ).html( "Dropped!" );
}
});
});
</script>
</body>
ajax加载的代码
<div class="droppable col-md-2" style="height:100px;border:1px solid gray">
<p> </p>
</div>
推荐答案
之所以添加该内容,是因为您当时尝试在不存在的元素上调用droppable
.要解决此问题,您可以使用可以附加到load
函数的回调函数,然后再运行其余函数.
This appends because you try to call the droppable
on a non-existing element at that moment. To solve this, you could use the callback function that can be attached to the load
function and run the rest after that.
$(document).ready(function(){
$("#site-preview").load("/site/preview", function() {
// Page loaded and injected
// We launch the rest of the code
$( ".draggable" ).draggable({
helper:'clone',
appendTo: 'body',
scroll: false
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
$( this ).addClass( "ui-state-highlight" ).find( "p" ).html( "Dropped!" );
}
});
});
});
您可以在此处中找到有关load
函数的其他信息.回调可以接受参数,并且可以用于例如检查其是否为404.
You can find other information about the load
function here. The callback can take arguments and can be used, for example to check if it's a 404 or not.
这篇关于jQuery拖放在Ajax上加载Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!