首页 > 解决方案 > 知道哪个 div 是 Sortable.js 的目标

问题描述

在 10 个 li 元素的列表中,我通过 Sortable.js 对列表进行排序。但我需要拖放 li 的项目的 id。我怎么会得到那个?

标签: sortablejs

解决方案


我正在使用 SortableJs 对同一类别列表中的项目进行排序,但也能够将项目从一个类别列表移动到另一个类别列表,反之亦然。

不确定这是否是您要查找的内容,但这是我获取目标容器(列表)ID 的方式。

  • event.oldIndex是项目的原始位置。
  • event.from是项目的原始容器元素(例如ul标签)
  • event.newIndex是项目的最终位置。
  • event.to是项目的最终容器元素(例如ul标签)

那就是说你可以做这样的事情:

/* If position did not change neither the containing list */
if (event.oldIndex === event.newIndex && event.from === event.to) { return; }

/* If position changed within the same category */
if (event.oldIndex !== event.newIndex) {
  const newPosition = event.newIndex
}

/* If product was moved to another category list */
if (event.from !== event.to) {
  /* Accessing `<ul data-id="10">` */
  const categoryId = event.to.dataset.id;
  /* Accessing `<ul id="list_on_the_right_11">` */
  const elementId = event.to.id;
}

希望它可以在某种程度上有所帮助。


推荐阅读