简体   繁体   English

javascript-模拟iOS中按钮上的点击事件(用手指点击)

[英]javascript - Simulate a click event (tap with finger) on a button in iOS

I'm trying to write a script that adds an item to the cart by simulating a click on the add-to-cart button on a webpage 我正在尝试编写一个脚本,通过模拟在网页上添加到购物车按钮上的点击,将商品添加到购物车中

<span id="cart-update">
<span class="cart-button">add to basket</span>
</span>

When I try to do the following on desktop, it works perfectly 当我尝试在台式机上执行以下操作时,它可以完美运行

document.getElementById('cart-update').click();

But when I try doing the same thing on iPhone it doesn't work. 但是,当我尝试在iPhone上执行相同的操作时,它不起作用。 I tried using the advice from this answer ( Simulate click event on mobile device ) and it didn't seem to work. 我尝试使用此答案中的建议( 在移动设备上模拟点击事件 ),但似乎没有用。 Can you help me out? 你能帮我吗?

Have you tried monitoring touch events at all, instead of click events? 您是否尝试过监视触摸事件而不是单击事件? Mobile browsers have their own events they're monitoring, some not considering "click" as an event at all 移动浏览器具有自己正在监视的事件,有些根本不将“点击”视为事件

From: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events 来自: https : //developer.mozilla.org/zh-CN/docs/Web/API/Touch_events

function startup() {
  var el = document.getElementsByTagName("button")[0];
  el.addEventListener("touchstart", handleStart, false);
  el.addEventListener("touchend", handleEnd, false);
  el.addEventListener("touchcancel", handleCancel, false);
  el.addEventListener("touchmove", handleMove, false);
  console.log("initialized.");
}

A way to work around it would be for a click/touch event to trigger a separate function entirely, like calling handleStart() in your function triggering the click event. 解决该问题的一种方法是使click / touch事件完全触发一个单独的函数,例如在函数中调用handleStart()来触发click事件。 Might be a better separation of concerns, too. 也可以更好地分离关注点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM