Javascript 一旦发生,如何禁用 onclick 事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3438557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:37:20  来源:igfitidea点击:

How to disable the onclick event once it happens?

javascripthtmlcsseventsonclick

提问by Rajasekar

I had a image which calls add_cart()JavaScript function when onclick()

我有一个图像调用add_cart()JavaScript 函数时onclick()

<img src="images/add.png" onclick="add_cart()">

I want the user to click the image only one time. When the user clicks it first time, add_cartfunction should be called. If he clicks second time no event should happen.

我希望用户只单击一次图像。当用户第一次点击它时,add_cart函数应该被调用。如果他第二次点击,则不会发生任何事件。

采纳答案by igaurav

If you are dealing this on jquery side,you can use jquery onemethod

如果你在 jquery 端处理这个,你可以使用 jqueryone方法

$(".myDiv").one("click", function(){  
    alert("this will happen only once");  
});

Cheers

干杯

回答by Anurag

<img src="images/add.png" onclick="add_cart(); this.onclick=null;">

回答by Bang Dao

Using

使用

<img src="images/add.png" onclick="this.onclick = function(){};add_cart();">

回答by Maxim Manco

window.onload = function() {
    document.getElementById('myImageId').onclick = handleImageClick;
}

var handleImageClick = function(e) {
    var target;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;

    if(target) {
        target.onclick = function(){}

        // do your stuff here
    }
}