如何让onclick函数只执行一次? [英] How to make onclick function execute only once?

查看:31
本文介绍了如何让onclick函数只执行一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个按钮上有这个用于谷歌分析的代码.我只需要执行一次,这样用户就无法通过多次按下按钮来更改统计信息.我尝试了类似主题的解决方案,但它们不起作用.请帮忙.这是我的代码.

I have this code for Google analytics on a button. I need it to be executed only once, so that the user can't change statistics by pressing the button many times. I tried solutions from similar topics, but they don't work. Please help. This is my code.

<script>
    function klikaj(i) {
        gtag('event', 'first-4', {
            'event_category' : 'cat-4',
            'event_label' : 'site'
        });
    }

    document.body.addEventListener("click", klikaj(i), {once:true})
</script>


<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">My button</div>

推荐答案

你可以像这样使用 removeAttribute(): document.getElementById('thumb0').removeAttribute("onclick");

you could use removeAttribute() like this: document.getElementById('thumb0').removeAttribute("onclick");

或者你可以让函数像这样返回 false:document.getElementById('thumb0').onclick = ()=>假

or you could let the function return false like this: document.getElementById('thumb0').onclick = ()=> false

这篇关于如何让onclick函数只执行一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆