Method to solve the problem of invalid binding click to dom element

  • 2021-07-21 07:26:37
  • OfStack

Before 1 straight encountered js plug-in generated elements, click event invalid problem, rebind is not good, finally find a solution, write it down here.

At the same time, it deepens the understanding of js event handling mechanism.

1. The event is unbound

In this case, 1 will not cause click to fail, but the click event will fail if:


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

Therefore, click events should have a good habit:


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

2. js plug-in loads dom asynchronously/dynamically

1 generally contains wait time/start time: WaitTime

Direct binding/listening is invalid at this time:


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

Solution 1:


$(function(){
 setTimeout(function{ 
 $('.container .btn').click(function(){
  //...
  })
 //.btn  Post-load event  
 },WaitTime) 
}) 

Solution 2 (event delegate, that is, delegate to parent element):


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

3. dom loaded asynchronously by ajax

You can add the click event to the body of the done () function Same as the event delegate method in 2.

4. Click on the link and there is no response

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


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

Solution:


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

Summary

1. Links related to event binding, event listening, and event delegation

2. Event capture and bubbling related links


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

Event capture

Parent element occurs first, child element follows

Event bubbling

Child element occurs first, parent element follows

3. javascript execution sequence


Related articles: