我在iPad Safari上安装了jQuery Mobile,出于某种原因,触摸滑动事件发生了两次.
人们在本周报告了与本周相同的问题,但我无法找到解释如何在不修改jQuery Mobile的情况下修复双重事件,我不想这样做. Thread on jQuery forums
滑动处理程序的以下元素绑定都具有相同的不正确的双事件结果,其中每次滑动都会调用两次警报.
应该如何绑定jQuery Mobile触摸事件以避免双重冒泡?
// Test 1: Binding directly to document with delegate() $(document).delegate(document,'swipeleft swiperight',function (event) { alert('You just ' + event.type + 'ed!'); }); // Test 2: Binding to document with on() handler recommended as of 1.7 with and without preventDefault $(document).on('swipeleft',function(event,data){ event.preventDefault(); alert('You just ' + event.type + 'ed!'); }); // Test 3: Binding to body with on() with and without event.stopPropagation $('body').on('swipeleft',data){ event.stopPropagation(); alert('You just ' + event.type + 'ed!'); }); // Test 4: Binding to div by class $('.container').on('swipeleft',data){ event.stopPropagation(); alert('You just ' + event.type + 'ed!'); });
解决方法
event.stopImmediatePropagation()是诀窍,与stopPropagation()不同.确保在document.ready中调用
jQuery on()方法似乎有所帮助.我能够使用任何元素选择器绑定事件,包括使用swipeup和从
here向下滑动
$(document).ready(function(){ $(document).on('swipeleft swiperight swipedown swipeup',data){ event.stopImmediatePropagation(); console.log('(document).Stop prop: You just ' + event.type + 'ed!'); }); });