Home >Web Front-end >JS Tutorial >Solution to the EVENT problem of losing dynamic binding after innerHTML_javascript skills

Solution to the EVENT problem of losing dynamic binding after innerHTML_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 17:33:341307browse

Use innerHTML to take out a piece of content and then innerHTML it back, then the original dynamically bound events will be lost, such as:
html:

Copy code The code is as follows:

Click


script:
Copy code The code is as follows:

document.getElementById('d1').onclick =function(){alert(1)};
var html=document.body.innerHTML;
document.body.innerHTML=html;

After executing this code, click d1 There was no response.
Solution:
Bind onclick to the parent element, use the bubble principle to determine whether the current element is d1, and if it is d1, execute
Copy code The code is as follows:

document.body.onclick=function(e){
var e=e||event;
var current=e.target||e.srcElement
if(current.id=='d1'){alert(1)}
}

This is also a fold The method will definitely affect the efficiency.
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