Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:33:34
Original
1256 people have browsed it

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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template