How to disable the onclick event once it happens?

2019-01-24 08:10发布

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.

4条回答
混吃等死
2楼-- · 2019-01-24 08:36

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

查看更多
够拽才男人
3楼-- · 2019-01-24 08:39
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
    }
}
查看更多
不美不萌又怎样
4楼-- · 2019-01-24 08:47

Using

<img src="images/add.png" onclick="this.onclick = function(){};add_cart();">
查看更多
趁早两清
5楼-- · 2019-01-24 08:50
<img src="images/add.png" onclick="add_cart(); this.onclick=null;">
查看更多
登录 后发表回答