jQuery draggable revert基于条件 [英] jQuery draggable revert based on condition
问题描述
我遇到了一个与jQuery draggable和droppable相关的问题。这是描述我想要做的事情。
I am having an issue related jQuery draggable and droppable. Here is description something what I want to do.
第一次:我有两个div。一个是< div id =selected>
,另一个是< div id =container>
。 container有10个< li>
,可以拖放到已选中。以下是代码:
First: I have two divs. One is <div id="selected">
and another is <div id="container">
. "container" has 10 <li>
which are draggable and droppable into "selected". Here is code:
<div id="selected">
<ul class="sortable-list">
</ul>
</div>
<div id="container">
<ul class="sortable-list">
<li>1</li>
<li>2</li>
<li>....</li>
<li>9</li>
<li>10</li>
</ul>
</div>
第二:我想允许任何5 < li>
从container到selecteddiv。如果有人试图添加第6个< li>
,那么它一定不允许用户使用它。那个将被插入selected的第6个< li>
必须使用 jQuery draggable option revert 。
Second: I want to allow any 5 <li>
s from "container" to "selected" div. If someone tries to add 6th <li>
, then it must not allow user to it. That is the 6th <li>
that is going to be inserted into "selected" must be reverted using jQuery draggable option revert.
ie $(#container li)。draggable({revert:true});
这是javascript代码。
i.e. $("#container li").draggable({ revert: true });
Here is javascript code for that.
$(document).ready(function(){
var total = 0;
$("#selected").droppable({
drop: function() {
total = $("#selected li").length;
//alert(total);
if (total >= 5) {
$("#container li").draggable({ revert: true });
} else {
// below code is not working
$("#container li").draggable({ revert: false }); // this is making whole feature weird. I can drag all the <li> anywhere
}
}
});
});
这个工作正常。
第三:但是当我将< li>
从selected拖到container时,selecteddiv只有4 <李>
秒。因此,在这种情况下,稍后用户应该能够将另一个< li>
添加到containerdiv中的selecteddiv中。但不幸的是它没有用。我尝试拖放到已选中的所有< li>
由于 if(total> = 5)<而被还原/ code> condition。
Third: But when I drag an <li>
from "selected" to "container", the "selected" div will have only 4 <li>
s. So in this situation, later on user should be able to add another <li>
into "selected" div from "container" div. But unfortunately it is not working. All the <li>
s I try to drag and drop into "selected" are being reverted due to if (total >= 5 )
condition.
任何人都可以帮我解决这个问题,使用 draggable revert 选项?请...
Can anyone help me to solve this out using draggable revert option? Please...
推荐答案
您可以使用 接受
选项,它使函数更容易实现,如下所示:
You can use the accept
option which takes a function to do this much easier, like this:
$("#selected ul").droppable({
accept: function() {
return $("#selected li").length < 5;
}
});
您可以在此处测试。当你拖出元素时, .length
会下降并且它会再次接受元素......没有理由变得更复杂:)
You can test it out here. When you drag elements out, the .length
goes down and it'll accept elements again...no reason to get any more complicated :)
这篇关于jQuery draggable revert基于条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!