如何对多个特定元素的droppable使用accept函数?

时间:2018-05-30 18:36:56

标签: jquery

我有可拖动和可放置的元素。我希望他们中的一些将被接受在一些droppables中,而另一些则不被接受(底部可以向上和其他方式删除),我想通过数据attribut对它们进行排序,我检查它是否具有特定值对于draggable和droppable元素之间的每个匹配。 我尝试使用接受功能,但我不知道如何使用它而没有特定元素。

html元素是这些:

<img  data-hand="hand-bottom-left" src="images\bottom-left-close.jpg">
<img  data-hand="hand-bottom-left" src="images\bottom-left-close.jpg">
<br>
<img data-hand="hand-up-left-close"  src="images\up-left-close.jpg">
<img data-hand="hand-up-left-close"  src="images\up-left-close.jpg">

这是js代码:

$("[data-hand*='hand']" ).draggable({
revert: true

});

$( "[data-hand*='hand']" ).droppable({
accept:function({
    if ($(img).attr('data-hand').indexOf('bottom') > -1)
    {
    // I don't know how to go on and if i'm in the right way    
    }
)

1 个答案:

答案 0 :(得分:0)

<强>更新

如果您希望droppable只能接受来自其他类别的项目,则只需检查拖动项目和目标droppable是否具有不同的data-hand值。

我为演示添加了一个jsFiddle。只有在接受放弃后才会弹出警报。

&#13;
&#13;
$("[data-hand*='hand']")
   .draggable({
          revert: true
    })
   .droppable({
          accept: function(e){
      	      return $(e).attr('data-hand') !== $(this).attr('data-hand');
          }, 
          drop: function(){
      	      alert('dropped');
          }
    });
&#13;
div{
  border: 1px dashed #aaa;
  width: 100px;
  display: inline-block;
  text-align: center;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>

<div data-hand="hand-up-left-close">1</div>
<div data-hand="hand-up-left-close">2</div>
<br>
<div data-hand="hand-bottom-left">3</div>
<div data-hand="hand-bottom-left">4</div>
&#13;
&#13;
&#13;

Accept选项要求selector引用可接受的元素,或者function返回布尔值以测试是否应该接受目标元素。

在您的情况下,您可以编写如下函数:

accept: function(){ 
     return $(this).attr('data-hand').indexOf('bottom') > -1;
}