在iphone上进行onclick工作

use*_*110 8 javascript

我一直在我的javascript中使用"onclick",但现在我希望它也适用于Iphone.是否有一种简单的方法可以使所有"onclick"像ontouchstart一样工作,支持ontouchstart?

或者我需要写两次所有脚本(一个使用onclick,另一个使用ontouchstart)?:S

注意:我不想使用jquery或任何其他库.

<!DOCTYPE html>
<title>li:hover dropdown menu on mobile devices</title>
<script>
window.onload = function () {
    if ('ontouchstart' in window) {
        // all "onclick" should work like "ontouchstart" instead
    }
    document.getElementById('hbs').onclick = function () {
        alert('element was clicked');
    }
}
</script>
<a id=id1 href=#>button</a>
Run Code Online (Sandbox Code Playgroud)

Mar*_*ijn 17

这篇文章得到了更多的关注,所以我将添加另一个常用的,更新的技巧:

// First we check if you support touch, otherwise it's click:
let touchEvent = 'ontouchstart' in window ? 'touchstart' : 'click';

// Then we bind via thát event. This way we only bind one event, instead of the two as below
document.getElementById('hbs').addEventListener(touchEvent, someFunction);

// or if you use jQuery:
$('#hbs').on(touchEvent, someFunction);
Run Code Online (Sandbox Code Playgroud)

let touchEvent应宣告出局的功能(也没有在的document.ready)在您的JavaScript的顶部.这样你就可以在所有的javascript中使用它.这也允许简单的jQuery使用.


老答案:

这解决了复制代码的需要(至少可以减少到最低限度).不确定你是否可以将它们结合起来

function someFunction() {
    alert('element was clicked');
}

document.getElementById('hbs').onclick = someFunction;
document.getElementById('hbs').ontouchstart= someFunction;

document.getElementById('hbs')
    .addEventListener('click', someFunction)
    .addEventListener('touchstart', someFunction);
Run Code Online (Sandbox Code Playgroud)