Event binding methods for DOM elements added dynamically in jQuery2.x and above

Keywords: JQuery

jquery dynamic add element cannot trigger the solution of binding event.

jquery dynamically adds a solution to an event that cannot trigger a binding.

 

Recently, we have encountered a problem in our work, that is, when we use jquery to dynamically add elements, we find that the elements added to the dynamic cannot trigger events. Later, I looked up some materials on the Internet and found that they had to be handled in this way

First, my error code:

<!DOCTYPE html>

<html>

<head lang="en">

    <meta charset="UTF-8">

    <title></title>

    <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.0/css/bootstrap.min.css">

    <script src="//cdn.bootcss.com/jquery/1.8.3/jquery.min.js"></script>



    <script>

        $(document).ready(function(){

        //Here is the dynamic add element

            $(".add").click(function(){

                var btn = $("<button class='newBtn btn btn-default'>New button</button>");

                $("body").append(btn);

            })<br><br>        //Here is adding events for the added elements

            $(".newBtn").click(function(){

                alert("Here is the event triggered by the newly added element");

            })



        })

    </script>

</head>

<body>

<button class=" add btn btn-default">add button</button>

</body>

</html>


Give me my solution. Don't spray, gods

 

Method 1: bind the live event (the live event is only supported under jQuery 1.9, not supported in higher version).

$(".newBtn").live("click",function(){ ///Under jQuery 1.9 (excluding 1.9), you can

    alert('Here are the events added by dynamic elements');

});


Method 2: bind ($(ParentEle).on("click",".thisEle",function() {}) with on () event

$("body").on("click", ".newBtn", function() {

    alert('Here are the events added by dynamic elements');

});
//ParentEle here is the parent element or ancestor element of thisEle,
// ParentEle can be document, body, etc.
//Note: if the function to be called at this time is an externally defined function, do not add () when calling, or the click event will be skipped to trigger the function directly

 

$("body").on("click", ".newBtn",aa );
 function aa(){
        alert('Here is the event added by the dynamic element ');
  }

Posted by EvilPrimate on Sun, 05 Apr 2020 00:04:13 -0700