How to disable the onclick event once it happens?

核能气质少年 提交于 2019-12-29 06:14:32

问题


I had a image which calls add_cart() JavaScript function when 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_cart function should be called. If he clicks second time no event should happen.


回答1:


If you are dealing this on jquery side,you can use jquery one method

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

Cheers




回答2:


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



回答3:


Using

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



回答4:


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
    }
}


来源:https://stackoverflow.com/questions/3438557/how-to-disable-the-onclick-event-once-it-happens

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