jQuery sortable cancel event if not valid

前端 未结 2 1268
逝去的感伤
逝去的感伤 2021-01-21 05:11

I have a list which is sortable. Before I start sorting, I want to check if all the elements of that list are valid. If not, cancel the event and leave the list intact.

相关标签:
2条回答
  • 2021-01-21 05:36

    The only way I have found to cancel a sort without hitting some jQuery UI bugs, is to asynchronously cancel the sort.

    Using the stop option as others have suggested, is not acceptable, as it allows the user to drag the item around on the screen first, and then cancels it when they are done. This does not satisfy the OP's original concern to "prevent" dragging of certain items.

    You will experience errors in jQuery UI if you try to cancel the sortable during the sort event. Errors like Uncaught TypeError: Cannot read property '0' of null

    Only solution I could get to work, does have a brief flash on the screen as the user begins to drag. But it immediately cancels the drag, and doesn't have any JS errors.

    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
        },
    });

    0 讨论(0)
  • 2021-01-21 05:50

    You can use the cancel method

    $("#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" );
            }
        }
    });
    

    Demo: Fiddle

    0 讨论(0)
提交回复
热议问题