English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Methods to Solve the Problem of Invalid Click Events Bound to DOM Elements

I have always encountered the problem that the click event is ineffective for elements generated by JavaScript plugins, and rebinding does not work either. Finally, I found the solution and write it down here.

At the same time, deepen the understanding of the JavaScript event handling mechanism.

1. event is unbound

In this case, it usually will not cause the click to fail, but in the following situations, the click event fails:

$(function(){
 $('.btn').unbind()
}
$('.btn').click(function(){
 //...
 }

Therefore, it is a good habit for the click event:

$(function(){
 $('.btn').click(function(){
 //...
 }
} 

2.js plugin asynchronous/dynamic loading dom

Generally contains waiting time/start time: WaitTime

This direct binding/listening is ineffective at this time:

$(function(){
 $('.container .btn').on('click',function(){
 //...
 }
} 

Solution1:

$(function(){
 setTimeout(function{ 
 $('.container .btn').click(function(){}
  //...
  }
 //.btn event after loading 
 },WaitTime) 
} 

Solution2(Event Delegation, i.e., delegated to the parent element):

$(function(){
 $('.container').on('click','.btn',function(){
 //...
 }
} 

3. ajax asynchronously loaded dom

  • You can add a click event in the done() function body
  • Same2The event delegation method in it.

4. Click the link without response

The following code will cause the a tag to have href but cannot jump

$(function(){
 $('a').on('click',function(e){
 e.preventDefault()
 //...
 }
} 

Solution:

$(function(){
 $('a').on('click',function(e){
 e.preventDefault()
 //...
 }
 $('a').unbind()
}

Summary

1.Event Binding, Event Listening, Event Delegation Related Links

2.Event Capturing and Bubbling Related Links

 target.addEventListener(type, listener[, options]);
 target.addEventListener(type, listener[, useCapture]);

Event Capturing

Parent elements occur first, followed by child elements

Event Bubbling

Child elements occur first, followed by parent elements

3.javascript execution order

That's all for this article. I hope the content of this article can bring some help to everyone's learning or work, and I also hope to get more support for the Yelling Tutorial!

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (When sending an email, please replace # with @ to report abuse, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like