jquery dynamically generates HTML code binding events

Source: Internet
Author: User

In today's work, we need to dynamically generate HTML code on the page, but find that the click event of the newly generated code is invalidated (the non-dynamically generated code has already bound the Click event), so there are many solutions on the web, many more complex, and the use of jquery is relatively old, So combined with their own tests on the Internet, found a solution.

I used the jquery is 1.9.11,jquery1.7 after the live method discarded, the new on and off method, my solution is to use the On method, first look at the code:

    <div class= "H3" >        
$ (function () {            $ (". Div"). Click (function () {                var h = "";                for (Var i=0;i<5;i++) {                    H + = "Here I add every click on <div class= "H3" > Finally add 5 lines 

$ (". h3"). On ("Click", "H3", {foo: "Text:"},function (event) {
alert (event.data.foo+this.textcontent);
});

Is it easy to choose <div class= "H3" > as the parent element to invoke the on method binding click event so that all elements under the parent element are bound to the Click event, and sometimes do not need to bind all of them? OK, just add the selector after "click" (That is, the child element you want to select), {foo: "Text:"}: The data passed to Event.data (parameter), in the handler we can call Event.data.foo to read the value of the passed function. Open the Browser debugging tool you can also get

In short, remember that if you want to bind dynamically generated element events, you must first find his parent element (the parent element cannot be dynamically generated, otherwise continue to look up), bind in the parent element, and then filter on OK, yes, I tested the hover event found no, did not go to the reason.

First, the problem description

After adding an HTML code dynamically with the jquery Append () method, it was found that the new element could not be obtained when binding the click event for the newly added element.

Second, the solution

The method of Niang recommendation is basically using the live () method

Official definition and usage of live ():

The live () method attaches one or more event handlers to the selected element, and specifies the function to run when these events occur. The event handlers attached through the live () method apply to the current and future elements of the matching selector (such as new elements created by the script).

Live () can be used to view jquery Live ()

The difference between live () and bind () is that live can not only bind events to existing elements in the page, but also add time to the elements that will be added dynamically in the future.

So I replaced bind () with live (), but reported a new error: TypeError: $ (...). Live is not a function

After the query found that the original jquery 1.9 and above have been unable to use Live (), you can use the on () method instead of live ().

The official definition and usage of on ():

The on () method adds one or more event handlers on the selected element and child elements. Since JQuery version 1.7, the On () method is a new alternative to the Bind (), Live (), and Delegate () methods.

Note: The event handlers added using the on () method apply to current and future elements (such as new elements created by the script).

The detailed use of on () can be viewed by jquery on ()

Three, the code demonstration

HTML page:

?
12345678910111213 <!DOCTYPE html>"en">  <meta charset="UTF-8">  <title>jQuery on()方法测试</title><body><button id="click1">Click me!</button><p>Hello,</p><script src="js/jquery.min.js"></script><script src="js/test.js"></script></body>

Test.js:

?
123456789 $().ready(function(){  $("#click1").bind("click",function(){    $("p").append("<div class=‘new‘><b>I‘m clicked!</b></div>");  });  //on方法要先找到原选择器(p),再找到动态添加的选择器(.new)  $("p").on("click",".new",function(){    $(this).remove();  });});

The 6th line in Test.js implements the bind click event for the dynamically added. New element. It should be noted that although the event is bound for. New, The On () method is bound to the original selector <p>, and then the. New is placed in the argument list, with the principle referring to the official definition and usage of the above on ().

jquery dynamically generates HTML code binding events

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.