简体   繁体   English

带有按钮的可排序 jQuery UI 列表

[英]Sortable jQuery UI list with buttons

Following the examples in the jQuery UI demo and documentation , I'm using this HTML:按照 jQuery UI演示文档中的示例,我正在使用此 HTML:

<ul class="sort">
  <li>
    <button>A</button>
  </li>
  <li>
    <button>B</button>
  </li>
  <li>
    <button>C</button>
  </li>
</ul>

And this JS:而这个JS:

$(function () {
  $('.sort').sortable();
})

But as seen in this JSFiddle example , the buttons are not drag-able.但正如在这个 JSFiddle 示例中所见,按钮不可拖动。

How can I make .sortable() work with buttons?如何使 .sortable() 与按钮一起工作?

Sortable provides a cancel selector to prevent sorting on specified elements. Sortable 提供了一个cancel选择器来防止对指定元素进行排序。 The default value includes <button> elements, and your sort handles are buttons, so sorting is prevented:默认值包括<button>元素,并且您的排序句柄是按钮,因此禁止排序:

cancel取消
Type: Selector类型:选择器
Default: "input,textarea,button,select,option"默认值:“输入、文本区域、按钮、选择、选项”
Prevents sorting if you start on elements matching the selector.如果从与选择器匹配的元素开始,则阻止排序。

To solve this, set the cancel selector to an empty string:要解决此问题,请将cancel选择器设置为空字符串:

 $('.sort').sortable({ cancel: '' });
 ul { list-style: none; margin: 0; padding: 0; width: 100px; } button { width: 100%; }
 <link href="//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="//code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <ul class="sort"> <li><button>A</button></li> <li><button>B</button></li> <li><button>C</button></li> </ul>

View on JSFIddle在 JSFiddle 上查看


Also, you can specify the draggable handles for sortable() by using the handle option :此外,您可以使用handle选项sortable()指定可拖动的handle

$('.sort').sortable({handle:'button'});

But in your case, the entire content of each <li> element is a <button> , so you won't need to specify it.但就您而言,每个<li>元素的全部内容都是一个<button> ,因此您无需指定它。

Ahhh, you know what?啊哈,你知道吗? jQuery UI prevents .sortable() from working on buttons by default, as stated in the .cancel() section of the documentation !默认情况下,jQuery UI 阻止 .sortable() 处理按钮,如文档的 .cancel() 部分所述 Clearing this default allows the buttons to be sort-able like in this updated example .清除此默认值允许按钮像在此更新的示例中一样可排序。

The functional JS/jQuery looks like this:函数式 JS/jQuery 如下所示:

$(function () {
  $('.sort').sortable({
    cancel: ''
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM