我在CMS管理页面中通过AJAX生成了多个列表,使用户可以浏览各种级别的内容。每个列表元素都是在用户单击上一个列表时生成的。我用jQuery:
$('#divid').on('click', 'ul', function() {
//code to modify lists
toggle_sortable();
});
现在我正在尝试添加一个切换按钮“拖动”以启用和禁用jQuery-UI sortable()
。但是,由于列表是动态生成的,因此无法完美实现。目前toggle_sortable()
看起来像:
function toggle_sortable() {
$('#drag').on('click', function(){
//statement to check if sortable() is enabled and change state accordingly
});
}
请帮助我在这种情况下找到解决方案。基本上我无法确定是否在特定列表中启用了sortable()
。
这是working DEMO动态初始化列表,并在单击按钮时切换列表上的可排序。
要启用/禁用可排序,您可以使用如下所示的功能:
$('#toggle').click(function() {
//check if sortable() is enabled and change and change state accordingly
// Getter
var disabled = $("#sortable").sortable( "option", "disabled" );
if (disabled) {
$("#sortable").sortable( "enable" );
$('#status').html('Sortable is now Enabled!!');
}
else {
$("#sortable").sortable("disable");
$('#status').html('Sortable is Disabled');
}
});
我不完全确定我理解了这个问题,但你仍然将点击处理程序堆积到相同的元素上。要么过滤掉那些有它的,要么每次添加,首先删除,如下所示:
```
$('#drag').off("click", doit).on('click', doit);
function() doit{
//statement to check if sortable() is enabled and change state accordingly
// $(this) will be jquery reference to "#drag" element
}
```
谢谢大家帮助!对不起,我无法准确解释这个问题。但是我使用了您的输入并最终得到以下代码:
$('#drag').on('click', function () {
event.preventDefault();
$(this).toggleClass('sortable');
if ($('#drag').hasClass('sortable')) {
$('#div ul').sortable();
} else {
$('#div ul').sortable('destroy');
}
});
上面的代码将启用和禁用sortable()
,但它不会将sortable()
应用于新附加的元素。对于那些我在附加这些列表的函数中使用以下行。
if ($('#drag').hasClass('sortable')) {
$('#ulid').sortable();
}