jQuery Sortable阻止用户将子项移动到父项

时间:2016-05-18 10:01:10

标签: javascript jquery jquery-ui-sortable

我在HTML中有这个列表:

<ol class="sortable subcategory_item">
    <li data-id="102">A</li>
    <li data-id="111">B</li>
    <li data-id="1712">GROUP A
        <ol class="group_items">
            <li data-id="105">GROUP MEMBER 1</li>
            <li data-id="108">GROUP MEMBER 2</li>
            <li data-id="109">GROUP MEMBER 3</li>
        </ol>
    </li>
    <li data-id="110">C</li>
    <li data-id="113">D</li>
</ol>

问题是我可以将GROUP A下的项目移动到其父级。

如何阻止GROUP MEMBER 1GROUP MEMBER 2GROUP MEMBER 3(或<ol class="group_items">内的项目移至GROUP A以上?

我目前正在使用jquery-sortable plugin,但如果我必须使用其他插件切换,我也没关系。

2 个答案:

答案 0 :(得分:1)

您可以简单地使用jQuery UI sortable,默认情况下您的行为方式:

$('.sortable,.group_items').sortable();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<ol class="sortable subcategory_item">
  <li data-id="102">A</li>
  <li data-id="111">B</li>
  <li data-id="1712">GROUP A
    <ol class="group_items">
      <li data-id="105">GROUP MEMBER 1</li>
      <li data-id="108">GROUP MEMBER 2</li>
      <li data-id="109">GROUP MEMBER 3</li>
    </ol>
  </li>
  <li data-id="110">C</li>
  <li data-id="113">D</li>
</ol>

答案 1 :(得分:0)

这是演示

&#13;
&#13;
$("#sortable").sortable({
  change: function(event, ui) {
    var currentClass = $(ui.placeholder)[0].classList[0];
    if (!$(ui.placeholder).prev().hasClass(currentClass) && !$(ui.placeholder).next().hasClass(currentClass))
      return false;
  }
});
$(".group_items").sortable();

$("#sortable").disableSelection();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-sortable/0.9.13/jquery-sortable-min.js"></script>
<script src="https://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<ol class="sortable subcategory_item" id="sortable">
  <li data-id="102" class="grp1">A</li>
  <li data-id="111" class="grp1">B</li>
  <li data-id="1712" class="grp1">GROUP A
    <ol class="group_items">
      <li data-id="105" class="grp">GROUP MEMBER 1</li>
      <li data-id="108" class="grp">GROUP MEMBER 2</li>
      <li data-id="109" class="grp">GROUP MEMBER 3</li>
    </ol>
  </li>
  <li data-id="110" class="grp1">C</li>
  <li data-id="113" class="grp1">D</li>
</ol>
&#13;
&#13;
&#13;