Home >Web Front-end >JS Tutorial >How to cancel click event in javascript

How to cancel click event in javascript

王林
王林Original
2021-10-25 15:40:358678browse

Javascript method to cancel a click event: If the event is bound using the onclick method, the event handler can be deleted to cancel the click event, such as [btn.onclick=null;].

How to cancel click event in javascript

#The operating environment of this article: windows10 system, javascript 1.8.5, thinkpad t480 computer.

We know that events in JavaScript are divided into DOM0 level and DOM2 level. If the event is bound using onclick method, then we can delete the event handler to cancel the click event.

btn.onclick=null;//删除事件处理程序

If you use the addEventListener() method to add an event, you can remove the event through removeEventListener(). Two points need to be noted:

1. The third parameter of removeEventListener() must be the same as addEventListener() The third parameter of the method is consistent.

2. Anonymous functions added through the addEventListener() method cannot be removed.

btn.aaddEventListener('click',function(){alert(1);},false);
btn.removeEventListener('click',function(){alert(1);},false);//没有用!

aaddEventListener and removeEventListener seem to pass in the same parameters, but in fact the second parameter of removeEventListener and the second parameter of aaddEventListener are completely different functions!

If you want to move out, you must do this:

 var fn=function(){
     alert(1);
 };
 btn.aaddEventListener('click',fn,false);
 btn.removeEventListener('click',fn,false);//有效

Recommended learning: javascript video tutorial

The above is the detailed content of How to cancel click event in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn