如果无效,jQuery可排序取消事件

Ped*_*rdo 1 jquery jquery-ui-sortable

我有一个可排序的列表.在开始排序之前,我想检查该列表的所有元素是否有效.如果没有,请取消该活动并保持列表不变.

你可以在这里找到代码 http://jsfiddle.net/DZYW5/4/

当我使用它时,事件被取消,但元素被删除.

start: function (event, ui) {
    if (!valid()) {
        return false;
        // it cancel's but the element is removed...
    }
}
Run Code Online (Sandbox Code Playgroud)

也许我应该实现"beforeStart"事件?建议?

Aru*_*hny 5

您可以使用cancel方法

$("#list").sortable({
    connectWith: ".connectedSortable",
    items: '.sortable-item',
    handle: '.handle',
    placeholder: "ui-state-highlight",
    stop: function (event, ui) {
        console.log('stop')
        if (!valid()) {
            $( this ).sortable( "cancel" );
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴

  • 这是我想出的解决方案 http://stackoverflow.com/a/37752652/213050 这在开始时取消了排序,并且没有任何 Js 错误。 (2认同)

H D*_*Dog 5

我发现取消排序而不遇到一些 jQuery UI 错误的唯一方法是异步取消排序。

使用其他人建议的停止选项是不可接受的,因为它允许用户首先在屏幕上拖动项目,然后在完成后取消它。这不能满足 OP 对“防止”拖动某些项目的最初关注。

如果您尝试在排序事件期间取消可排序,您将在 jQuery UI 中遇到错误。像这样的错误Uncaught TypeError: Cannot read property '0' of null

我可以开始工作的唯一解决方案是,当用户开始拖动时,屏幕上会出现短暂的闪烁。但是它立即取消了拖动,并且没有任何JS错误。

var isCancel = false;
element.sortable({
    start: function() { isCancel = false; },
    sort: function(event, ui) {      // prevent dragging if row has dynamically assigned class
	if (ui.item.hasClass('no-drag')) {
	    isCancel = true;
	    // allow current jQuery UI code to finish runing, then cancel
	    setTimeout(function() {
		element.sortable('cancel');
	    }, 0);
	}
    },
    stop: function() {
    	if (isCancel) return;
    	// your normal processing here
    },
});
Run Code Online (Sandbox Code Playgroud)