SoFunction
Updated on 2025-04-13

Solution to the EVENT problem of losing dynamic binding after innerHTML

Use innerHTML to extract a piece of content and then return to innerHTML, then the dynamically bound events will be lost, such as:
html:
Copy the codeThe code is as follows:

<body><div id='d1'>Click</div></body>

script:
Copy the codeThe code is as follows:

('d1').onclick=function(){alert(1)};
var html=;
=html;

After this code is executed, clicking d1 will not react.
Solution
Bind onclick to the parent element, use the bubble principle to determine whether the current element is d1, if it is d1, execute it
Copy the codeThe code is as follows:

=function(e){
var e=e||event;
var current=||
if(=='d1'){alert(1)}
}

This is also a compromise method and will definitely affect efficiency.