我问过类似的问题,但没有得到真正令人满意的答案,所以我会在这里再试一次。当我使用这样的代码时:
$("#element") .on( 'click', function() {
// do something
} )
.on( 'touchstart', function(e) {
e.preventDefault();
// do the same thing but on touch device like iPad f.e.
// and more over PLEASE do not fire the click event also!
} );
我期望点击事件永远不会永远不会触发(因为浏览器应该通过事件处理的层次结构)但实际上当我触摸元素时,比方说 20 次,点击事件也触发一次.为什么?
我也尝试过类似的东西:
$("#element") .on( 'click', function() {
// do something
} )
.on( 'touchstart', function(e) {
e.preventDefault();
e.stopPropagation();
// do the same thing but on touch device like iPad f.e.
// and more over PLEASE do not fire the click event also!
return false;
} );
它似乎更坚固但不防弹。 所以我必须这样做:
$("#element") .on( 'click', function() {
if ( !touchdevice ) {
// do something
};
} )
.on( 'touchstart', function(e) {
e.preventDefault();
e.stopPropagation();
// do the same thing but on touch device like iPad f.e.
// and more over PLEASE do not fire the click event also!
return false;
} );
这似乎有效但非常愚蠢,不是吗?任何有想法的人这是关于什么的?谢谢!
编辑: 所以我真的不得不做类似的事情:
var touched;
$("#element") .on( 'click', function() {
if ( !touched ) {
// do something
};
} )
.on( 'touchstart', function(e) {
e.preventDefault(); // actual senseless here
e.stopPropagation(); // actual senseless here
touched = true;
// do the same thing but on touch device like iPad f.e.
// and more over PLEASE do not fire the click event also!
return false; // actual senseless here
} );
小伙伴们加油!必须有一种安全的通用方法来在同一元素上使用 touchstart 和 click 事件,以确保不会触发 click 事件(两次)以处理触摸感应浏览器和常规浏览器(甚至是新的组合浏览器)。你会怎么做?
最佳答案
I am expecting that the click event is never never never fired (because of the hierarchy with which browser should work through the events) [...]
您对 even.preventDefault()
的期望有误。
event.preventDefault()
阻止浏览器为该元素/事件组合执行的默认操作。例如。提交表格或以下链接。它不会阻止任何其他事件处理程序的执行。
e.stopPropagation()
防止事件冒泡,这样添加到祖先的事件处理程序就不会被执行。
但是,您不能使用这些方法中的任何一种来阻止执行不同事件 的处理程序,因此设置标志似乎确实是执行此操作的正确方法。
关于javascript - e.preventDefault() 不是防弹的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25671053/