Using click() on links in Android Stock Browser not working

家住魔仙堡 提交于 2019-12-25 16:43:12

问题


I want to trigger a click on a link with JavaScript but have problems getting it to work on the Android Stock Browser. The following code works fine in Chrome (Desktop, Mac) and Safari (iOS) but not in the Android Stock Browser (Samsung Galaxy S3):

<a href="test" id="a">One</a>
<a href="test" id="b">Two</a>

<script>
document.getElementById('a').addEventListener("click", function (e) {
    e.preventDefault();
    document.getElementById('b').click();
});

document.getElementById('b').addEventListener("click", function (e) {
    e.preventDefault();
    alert("test");
});
</script>

http://jsfiddle.net/xYfdF/7/

When replacing the links with buttons it starts working on Android as well: http://jsfiddle.net/xYfdF/8/

Any idea what the problem is or how to achieve this otherwise?


回答1:


I found the solution here. Its pure JS, not jquery, but might help to solve missing click() on android stock browsers:

<a href="http://stackoverflow.com/" id="link">click here</a>

<script type="text/javascript">
    //same as: document.getElementById("link").click()
    var clickEvent = document.createEvent('MouseEvent');
    clickEvent.initEvent('click', true, true);
    document.getElementById("link").dispatchEvent(clickEvent);
</script>



回答2:


you need to convert your click events to touch events using Jquery like below

<script type="text/javascript">
    jQuery(document).ready(function() 
    {
       jQuery('#a').bind("touchstart touchend touchmove click",function(event) 
       {
    event.preventDefault();
         jQuery('#b').click();
       });

      jQuery('#b').bind("touchstart touchend touchmove click",function(event) 
       {
    event.preventDefault();
         alert('Test');
       });
    });
 </script>


来源:https://stackoverflow.com/questions/16936066/using-click-on-links-in-android-stock-browser-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!