简体   繁体   中英

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. 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

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. Might be a better separation of concerns, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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