JavaScript to dynamically inserted element to the event binding

Since the actual needs, sometimes necessary to dynamically insert HTML page content, and bind the event handler inserted node. We know that content is inserted into an HTML document with Javascript, there are two ways,

One is to write HTML code into JS, and then inserted into the document;

Alternatively, the data acquired from the server via ajax manner, then js the acquired data into the document after treatment;

Both methods have their own characteristics, this article will analyze the new elements in the document is inserted into the event binding problem, and assume the newly inserted object is not inline event binding (that is, without a form similar to <a onclick=""> ). All examples will use jQuery and native Javascript.

I.: HTML code is stored in JS, see the following code:

Copy the code
    <body> 
    <P> line 1 </ P> 
    <P> line 2 </ P> 
    <P> The first three rows </ P> 
    <Script> 
    var appendhtml = document.createElement ( "P") ; 
    appendhtml.innerHTML = "this is inserted content"; 
    document.body.appendChild (appendhtml); 
    var nodep document.getElementsByTagName = ( "P"); 
    for (var I = 0; I <nodep.length; I ++) { 
    nodep [I] .onclick = function () { 
    the console.log ( "the Click the Event!"); 
    } 
    } 
    </ Script> 
    </ body>
Copy the code

The above native code is generated Javascript, when this code is executed, js generates a fourth P-tag on the page, and click when the four labels will trigger a corresponding action. It is not to say, with the js generated HTML content, can be bound corresponding incident? The answer is no, the script tag in the code above, there are two sections of code, code section one is used to insert content into the HTML code segment two is used to bind the event, if a segment of code and code section two swap position, find the JS generate a fourth P tag does not bind the click event. The test with the following code jquery:

1
2
3
4
5
6
$(function(){
$("p").click(function(){
console.log("Click Event");
})
$("< p >这是生成的内容</ p >").appendTo("body");
})

Findings, too, the success of the implementation of the event is also directly related to the code sequence segments. In fact, the original good analysis, whether it is the use of getElementsByTagName or jquery selectors when content needs has not been inserted, the selector will select elements on the page already exists, so there is no prior elements are not binding events.

However, the reality is that the work may need to later-generated element binding on the event, and register the event handler. For example this site messaging system, first load the comment will only show a fixed number of pieces, if more than a certain number of reviews, and the rest will be loaded with ajax way. All messages have a final reply feature, click on the corresponding message can be restored, that is, dynamically loaded up the message, perhaps to bind the click event, and the reply function registered mail. Of course, lazy way is to load up ajax content and then register a click and then bind a corresponding function, but it has increased the code redundancy, increased system overhead, but also makes the code becomes difficult to understand. So what better solution is it?

technology sharing

Reply function Message system

 

Can understand, regardless of JS HTML content is not generated, as long as there is no cross-domain elements in all the pages belong to this page, are able to bind the event, JS There is a very important concept called event bubbling, simply, is generated by the event sub-elements, it would have been bubbling to the top of the parent element, the parent element and can be monitored. See below:

technology sharing

Event bubbling 

Well, I can not monitor events generated in the bubbling element of the parent element is inserted, and the corresponding callback function? The answer is definitely yes. Consider the following example, note that the content of the page is the last face in the insertion of the JS code.

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

It was found that all of the P element clicks have had output, the code runs successfully. Here we use jQuery's delegate functions, look at the official explanation :

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
According to a particular root element, the one or more events registered to the specified elements, regardless of whether this element now exists.

In the above jQuery1.7.3 version, on ways to do this, there are examples of official explanation, not repeat them here.

For example, there are some cases repeatedly access dynamic content from the background to the foreground, when clicked will trigger several times, but also use $ ( "body") undelegate ();. Prior to unbind and then rebind again.

1
2
3
4
$( "body" ).undelegate();
$( "body" ).delegate( ".reply_check_btn" , "click" , function () {
     alert( 'adsadsa' );
});

Guess you like

Origin www.cnblogs.com/planetwithpig/p/11959462.html