简体   繁体   中英

How to attach event to the newly added anchor using jquery

I trying to attach a click event for the newly added anchor tag(.he) after the #foo anchor tag. But the click event is not happening. I have used (.on). Can you guys help me in this ? *

        <!DOCTYPE html>
        <html>
        <head>
        <title>Attaching event</title>
       <style>p { background:yellow; margin:6px 0; }</style>
       <script src="js/jquery.js"></script>
        </head>
    <body>
    <p>Hello</p>
    how are
    <p>you?</p>

    <button>Call remove() on paragraphs</button>

    <a id="foo" href="#" style="display:block">Testing the bind and unbind</a>


    <script>
        $("button").on('click',function () {

            $("#foo").after("<a class='he' href='#'>asdfasdf</a>");

        });
        $(".he").on('click', function(){
                alert("test");
        });     

    </script>
</body>

You have to delegate to a static parent element like this

$(document).on('click','.he',function(){

//code here
});

Use event delegation

$("body").on("click", ".he", function() {
    alert("test");
});

Instead of body you can use any static parent element of .he .

use .live . and don't forget to add your code inner jquery clousure

<script>
    $(function(){
        $("button").on('click',function () {
            $("#foo").after("<a class='he' href='#'>asdfasdf</a>");
        });

        $(".he").live('click', function(){
            alert("test");
        });
    });
<script>

you will have to put the below code inside $("button").click block.

  $(".he").on('click', function(){
                    alert("test");
            }); 

Link for jsfiddle http://jsfiddle.net/wbWLE/

You can instead bind the click event to the anchor before appending it to the DOM like this:

 var $he = $("<a class='he' href='#'>asdfasdf</a>").on('click', function(){
                 alert("test");
            })
 $("#foo").after($he);

You can either attach a handler to the anchor directly before it is appended into the document:

$("button").on('click',function () {
   $("<a class='he' href='#'>asdfasdf</a>")
      .on('click', function(){
         alert("test");
      })
      .insertAfter("#foo");
});

or bind a delegate handler on the document that will catch all clicks on anchors with he as their class:

$(document).on('click', 'a.he', function() {
   alert("test");
});
$("button").on('click',function () {
   $("<a class='he' href='#'>asdfasdf</a>").insertAfter("#foo");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM