我有一个显示项目列表的 jQuery Mobile 应用程序。单击向上或向下按钮时,我可以选择一个项目并将其向上或向下移动。
当我通过单击按钮向上或向下移动项目时,显示的项目及其项目 ID 将被交换。然后我发送一条 ajax post 消息,其中包含项目移动的步骤。
我看到的是,如果我点击得太快,有时项目不会按照预期的方式移动。也可能发生 item-id 重复的情况,就好像该函数在 item-id 交换操作的中间被中断了一样。
这是已知功能吗?有没有办法避免这种情况?
这是移动元素的代码
$("#btnListUp").on( "click", function(evt)
{
if( selectedItem && !selectedItem.hasClass('ui-first-child') )
{
var prev = selectedItem.prev();
var prevId = prev.attr('item-id');
var thisId = selectedItem.attr('item-id');
var step = (parseInt(prevId) - parseInt(thisId))+'';
prev.attr('item-id', thisId );
selectedItem.attr('item-id', prevId );
prev.detach().insertAfter(selectedItem);
$('#ShopList').listview('refresh');
$.ajax( {type: 'POST', url: thisId+'/moveUp', data : step,
contentType :'applicatio/octet-stream' } );
}
});
$("#btnListDown").on( "click", function(evt)
{
if( selectedItem && !selectedItem.hasClass('ui-last-child') )
{
var next = selectedItem.next();
var nextId = next.attr('item-id');
var thisId = selectedItem.attr('item-id');
var step = (parseInt(nextId) - parseInt(thisId))+'';
next.attr('item-id', thisId );
selectedItem.attr('item-id', nextId );
next.detach().insertBefore(selectedItem);
$('#ShopList').listview('refresh');
$.ajax( {type: 'POST', url: thisId+'/moveDown', data : step,
contentType :'applicatio/octet-stream' } );
}
});
最佳答案
这是预期结果,您已将点击事件绑定(bind)到 btnListUp 和 btnListDown 元素。下一个点击事件不会等待第一个完成,第一个也不会推迟第二个。
在您的情况下,只有两种解决方案是可能的。
方案一
首先,在第一次点击后,取消绑定(bind)按钮的点击事件,如下所示:
$("#btnListUp").on( "click", function(evt)
{
$(this).off('click');
其次,在ajax成功和错误回调期间再次绑定(bind)点击事件。这是一种方式。
解决方案2
第二种解决方案更简单,但有时您将无法使用它:
看看这个链接:
Disable jquery function after 1 click, to prevent multiple executions
关于javascript - jQuery Mobile 中点击过快会跳过某些操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15462013/