The solution when the newly added element cannot be monitored by event delegation

 

In JS, using event delegation to listen to events is the best solution to achieve the effect of a common event handler for newly added elements after page loading.

However, I encountered a helpless situation when referencing third-party code is a non-event delegation method and cannot be modified to an event delegation method.

In the experiment, it was found that the corresponding JS file can be re-referenced, so as to achieve the effect of re-executing JS after a newly added element, so the newly added element node is also logically monitored with events.

The sample code is as follows:

HTML:

1 <script src="/static/home/js/main.js" id="mainjs"></script>

JS:

1      // jQuery syntax
 2      function refreshjs() {
 3          $('#mainjs').remove(); // remove old js import tags
 4          $(' < script src ="/static/home/js/main .js" id ="mainjs" ></ script > ').appendTo(document.body); // Re-introduce the corresponding js file, re-execute js, and add event monitoring again
 5      }
 6      
7      refreshjs() ; //Called after adding a new element node, or other events that need to be re-added

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324809541&siteId=291194637