如何使单个组合框可排序?

How to make a single combobox sortable?

我正在尝试使单个组合框可排序。 Jquery UI 关于 sortables 的文档提到,sortable 应该像这样设置:

$( ".selector" ).sortable();

当我放入选择器后,它使我所有的 Select2 元素都可以排序:

$("ul.select2-selection__rendered").sortable()

我想使特定 div 中只有一个元素可排序。我尝试从我的浏览器复制 CSS 选择器路径,但出现错误:

var outpatient = document.querySelectorAll('#department-outpatient > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > span:nth-child(2) > span:nth-child(1) > span:nth-child(1) > ul:nth-child(1)')[0];
outpatient.sortable({
  // ...
});

TypeError: outpatient.sortable is not a function

当您使用 querySelectorAll() 检索它时,outpatient 变量将保存一个 Element 对象。 sortable() 依赖于 jQuery,因此需要在 jQuery 对象上调用。因此,要解决此问题,您可以从 outpatient 创建一个 jQuery 对象,然后对其调用 sortable()

var outpatient = document.querySelectorAll('#department-outpatient > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > span:nth-child(2) > span:nth-child(1) > span:nth-child(1) > ul:nth-child(1)')[0];
$(outpatient).sortable({
  // ...
});

更进一步,将 jQuery 本身用于 select 元素。另请注意,我确信您可以简化 selector。这似乎太具体了。

var $outpatient = $('#department-outpatient > div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > span:nth-child(2) > span:nth-child(1) > span:nth-child(1) > ul:nth-child(1)');
$outpatient.sortable({
  // ...
});