jQuery Click事件在移动设备上不起作用 [英] Jquery click event not working on mobile device
问题描述
我正在尝试使以下JSFiddle适用于平板电脑/移动设备(例如触摸"和点击").
https://jsfiddle.net/lkw274/7zt1zL0g/87/ >
<div class="user-navigation">
<a class="mobile-menu-new" href=""><span></span>Menu</a>
</div>
$(document).ready(function() {
$(".user-navigation a.mobile-menu-new").click(function (e) {
e.preventDefault();
$(".user-navigation a.mobile-menu-new").toggleClass("current");
});
});
.current { background: #F00;}
预期行为: 单击菜单"时,通过触摸或用鼠标单击,背景将突出显示为红色,直到应删除班级时再次单击该背景,然后将红色背景移除,并将其恢复为原始状态.
当前行为: 单击菜单"时,通过在移动/平板电脑设备上触摸,背景会突出显示为红色,但是第二次单击菜单"时,该类不会被删除.
任何人都可以帮助您了解如何针对平板电脑/移动设备修改此代码吗?
我已经在下面的StackOverflow链接中尝试过该解决方案,但是一旦实现,点击后该功能就不会起作用.
> document-click-function-for-touch-device >
谢谢.
看起来像事件委托是之所以这样做,是因为在修改目标元素时,绑定似乎失败了.
尝试以下操作(在我的iPhone/Chrome上可以使用).
$(document).ready(function() {
$(".user-navigation").delegate("a.mobile-menu-new", "click", function (e) {
e.preventDefault();
$(this).toggleClass("current");
});
});
请注意,由于您似乎正在使用 I am trying to make the below JSFiddle work for tablet/mobile devices (e.g. 'on touch' as well as 'click'). https://jsfiddle.net/lkw274/7zt1zL0g/87/jQuery 1.6
(根据您的小提琴),因此我已经使用了.delegate
,否则,对于jQuery 1.7+
,您可以使用
<div class="user-navigation">
<a class="mobile-menu-new" href=""><span></span>Menu</a>
</div>
$(document).ready(function() {
$(".user-navigation a.mobile-menu-new").click(function (e) {
e.preventDefault();
$(".user-navigation a.mobile-menu-new").toggleClass("current");
});
});
.current { background: #F00;}
Expected behaviour: On clicking 'Menu', either by touch or with clicked with mouse, the background is highlighted red until it is clicked again when the class should be removed, removing the red background and returning it to its original state.
Current behaviour: On clicking 'Menu', by touch on mobile/tablet device, the background is highlighted red however the class is not removed when 'menu' is clicked for the second time.
Could anyone help to understand how this code needs to be modified for tablet/mobile devices?
I have tried the solution in the below StackOverflow link however this did not function on click once implemented.
document-click-function-for-touch-device
Thanks in advance.
Looks like event delegation is the way to do this since, when you modify the target element, bind seems to fail.
Try the following (works on my iPhone/Chrome).
$(document).ready(function() {
$(".user-navigation").delegate("a.mobile-menu-new", "click", function (e) {
e.preventDefault();
$(this).toggleClass("current");
});
});
Please note I have used .delegate
since you seem to be using jQuery 1.6
(as per your fiddle) as otherwise, with jQuery 1.7+
, you could use .on
like below.
$(document).ready(function() {
$(".user-navigation").on("click", "a.mobile-menu-new", function (e) {
e.preventDefault();
$(this).toggleClass("current");
});
});
这篇关于jQuery Click事件在移动设备上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!