On the solution to the event problem of dynamic binding after innerHTML loss _javascript tips

Source: Internet
Author: User
Use innerHTML to remove a piece of content and then innerhtml back, then the original dynamically bound event will be lost, such as:
Html:
Copy Code code as follows:

<body><div id= ' D1 ' > click </div></body>

Script
Copy Code code as follows:

document.getElementById (' D1 '). Onclick=function () {alert (1)};
var html=document.body.innerhtml;
document.body.innerhtml=html;

After this code is executed, clicking D1 is no response.
Workaround :
The onclick binding to the parent element, using the bubble principle, to determine whether the current element is D1, if the D1 is executed
Copy Code code 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 compromise approach that will certainly affect efficiency.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.