touchend handler fires twice

2020-07-22 03:26发布

On a webapp on iOS, I have a bunch of buttons that respond only to touchend (as a shortcut to the click delay in mobile safari). When I stick an alert in the handler, then a subsequent tap of any other button on the page fires this original handler even though they have their own handlers. Here's some sample code that illustrates the problem:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />

<script type="text/javascript">

function clickAlert(evt) {
    alert('btn clicked');
}

function clickData(evt) {
    var div;

    div = document.getElementById('data');
    div.innerHTML += 'btn2 click: ' + (new Date().getTime()) + '<br/>';
}

function loadHandler() {
    var btn;

    btn = document.getElementById('btn-click-alert');
    btn.addEventListener('touchend', clickAlert, false);
    btn = document.getElementById('btn-noclick');
    btn.addEventListener('touchend', clickData, false);
}

window.addEventListener('load', loadHandler, false);
</script>

</head>
<body>

<button id="btn-click-alert">Click to alert</button>
<button id="btn-noclick">No alert here</button>
<div id="data"> </div>
</body>
</html>

Can someone help?

Thanks!

1条回答
冷血范
2楼-- · 2020-07-22 03:56

I believe the visual, full-page alert being triggered on touch end is interfering with the touch event cycle. Try to call the alert after yielding to the DOM. eg.

setTimeout(function() {
    alert('btn clicked');
}, 0);
查看更多
登录 后发表回答