简体   繁体   中英

How to unbind click event for anchor tag

Trying to work with the following code to unbind click after a certain time for anchor tags.

 $('a').click((e)=>{
        x = e.target;
        e.preventDefault();
        setTimeout(function(){ 
            unBind(x) }, 500);
});

unBind=(x)=>{
    $(x).unbind('click').click();
}

But this is not working. The unbinding is not happening it seems to be. But the code does work if I use class selectors instead.

$('.className').click((e)=>{
        e.preventDefault();
         setTimeout(function(e){ 
                $('.className').unbind("click").click();
            }, 500);
    })

Could someone help me resolving the issue with anchor tag. Thanks!

Edit: Updated the code removing $(this) from setTimeout

I tried to replicate the HTML that you are describing, and I copied your MRE from the first section, added console logging (randomness as an identity for each call), and it seems to work.

 $('a').click((e)=>{ x = e.target; e.preventDefault(); console.log("click " + Math.random()); setTimeout(function(){ unBind(x) }, 500); }); unBind=(x)=>{ console.log("unbind " + Math.random()); $(x).unbind('click').click(); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a class="className" href="#f">f</a>

Tried a little workaround and below is the solution I found.

 $('a').click((e)=>{        
            e.preventDefault();
            setTimeout(()=>{window.location.href = $(e.target).attr("href");},500);
    
    }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM