Event binding issue of dynamically generated content in HTML "reprint"

Source: Internet
Author: User

Transfer from http://www.hitoy.org/event-binding-problem-of-dynamically-generated-content.html

Because of the actual need, it is sometimes necessary to insert HTML content dynamically into the Web page and bind the event handler in the inserted node. We know that using JavaScript to insert content into an HTML document, there are two ways, one is to write HTML code to write JS, and then insert into the document, the other is through the Ajax way, from the server to obtain data, and then use JS to get the data processed and inserted into the document Each of the two methods has its own characteristics, this article analyzes the issue of the event binding of the newly inserted element in the document, and assumes that the newly inserted object does not do inline event binding (that is, not like <a onclick= "" >). All of the examples will use jquery and native JavaScript.

Situation One: HTML code is stored in JS, see the following code:
    • <body>
    • <p> 1th line content </p>
    • <p> 2nd line content </p>
    • <p> 3rd line content </p>
    • <script>
    • var appendhtml=document.createelement ("P");
    • appendhtml.innerhtml= "This is the inserted content";
    • Document.body.appendChild (appendhtml);
    • var nodep=document.getelementsbytagname ("P");
    • for (var i=0;i<nodep.length;i++) {
    • nodep[i].onclick=function () {
    • console.log ("click event!");
    • }
    • }
    • </script>
    • </body>

The above code is generated with native JavaScript, when this code executes, JS will generate a fourth P tag in the page, and click on these four tags, will trigger the corresponding action. So is it that the HTML content generated by JS can be bound to the corresponding event? The answer is no, in the script tag of the above code, there are two code snippets, code snippet one is used to insert content into the HTML, code snippet Two is used to bind the event, if the code snippet one and code snippet two interchange position, found that JS generated fourth P tag is not bound on the Click event. The jquery test with the following code:

    • $(function(){
    • $("p").click(function(){
    • console.log("Click Event");
    • })
    • $("<p>这是生成的内容</p>").appendTo("body");
    • })

It is also found that the success of an event execution is also directly related to the order of the code snippet. In fact, the original is very good analysis, whether the use of getElementsByTagName or jquery selector, when the required content has not been inserted, the selector will only select the page is already existing elements, so there is no element in advance can not bind the event.

However, the reality is that it is possible to bind the resulting elements to events on the job, and register the event handler functions. For example, the message system on this site, the first load will only show a fixed number of comments, if the comments more than a certain amount, the rest will be loaded in Ajax way. All the message finally has a reply function, click can restore the corresponding message, that is, dynamic loading up the message, perhaps to bind the click event, and register on the reply message function. The lazy way, of course, is to register a click for the AJAX load and then bind the corresponding function again, but this increases the redundancy of the code, adds overhead, and makes the code difficult to understand. So what's the better way to solve it?

Reply function of message system

It can be understood that whether the HTML content is not JS generated, as long as there is no cross-domain, all the elements within the page belong to this page, can bind events, JS has a very important concept called event bubbling, simply speaking, is the child element generated events, will always bubble to the top-level parent element, and can be monitored by the parent element. Please see:

Event bubbling

So, can I monitor the events generated by bubbling on the parent element of the inserted element and callback the corresponding function? The answer is of course yes. To take a look at the following example, note that the content inserted in the Web page is at the end of the JS code.

    • <script>
    • $(function(){
    • $("body").delegate("p","click",function(){
    • console.log("Click Event");
    • })
    • $("<p>这是生成的内容</p>").appendTo("body");
    • })
    • </script>

This is the discovery that all P-element clicks produce output, indicating that the code is running successfully. Here we use the delegate function of jquery and take a look at the official explanation:

Attach a handler to one or more events for all elements this match the selector, now or in the future, based on a specific Set of root elements.
Registers one or more events on the specified element, depending on the specific root element, whether or not the element exists now.

In the version above jQuery1.7.3, the on method can also do this thing, the official has the example explanation, here does not repeat.
jquery provides a powerful API to solve this problem, how does native JS do it? Here is a simple solution that we hope will help you understand the principle of bubbling.

    • <script>
    • function gelegate(action,selector,callback){
    • document.addEventListener(action,function(e){
    • if(selector==e.target.tagName.toLowerCase()||selector==e.target.className){
    • console.log("Click Event");
    • callback();
    • }
    • })
    • }
    • gelegate(‘click‘,‘p‘,function(){});
    • var appendhtml=document.createElement("p");
    • appendhtml.innerHTML="这是插入的内容";
    • document.body.appendChild(appendhtml);
    • </script>

Note that the above code is for Chrome only and the actual project may have compatibility issues.
I see, welcome to shoot brick spit groove.

Event binding issue of dynamically generated content in HTML "reprint"

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.