1

I have this page:

<html>
<head></head>
<body>

<div id="elem"></div>
<button id="addElem">Add Element</button>

<script src="jquery-1.9.1.js" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {

        //add element to elem div
        $("#addElem").click(function () {
            $("#elem").append('<a id="test" href="#">this is a test</a><br />');
        });

        //remove added elements on click event
        $("#test").on("click", function(){
            alert(12);
        });

    });
</script>

</body>
</html>

What it is doing, is adding a link and I would like to be able to click on the added link and display an alert message but the alert is not working. What am I missing?

mpora
  • 1,411
  • 5
  • 24
  • 65
  • possible duplicate of [.delegate() vs .on()](http://stackoverflow.com/questions/8359085/delegate-vs-on) You aren't using the correct syntax for delegated events with .on. Your current usage is identical to using `.click(function(){...` – Kevin B May 01 '13 at 20:56
  • Isn't the problem here that jquery is running *before* the element with #test is even available? – keithwyland May 01 '13 at 20:58

3 Answers3

5

Change it to...

$("#elem").on("click", "#test", function(){
        alert(12);
});

The jQuery blog has a great explanation for this.

$(elements).on( events [, selector] [, data] , handler );

When a selector is provided, .on() is similar to .delegate() in that it attaches a >delegated event handler, filtered by the selector. When the selector is omitted or null >the call is like .bind(). There is one ambiguous case: If the data argument is a string, >you must provide either a selector string or null so that the data isn’t mistaken as a >selector. Pass an object for data and you’ll never have to worry about special cases.

Blake Plumb
  • 6,779
  • 3
  • 33
  • 54
1

You do not have an anchor for the event. Since you have no other wrapper, add the document to that:

$(document).on("click", "#test", function(){
    alert(12);
});

NOTE: This will ONLY work on the first click as you would be adding multiple ID's that would be duplicates.

Better way:

$("#addElem").click(function () {
    $("#elem").append('<a class="test" href="#">this is a test</a><br />');
});
$(document).on("click", ".test", function(){
    alert(12);
});
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100
0

You can attach the function to the created element at the time you create it:

$("#elem").append($('<a>', {
  id: "test.
  href: "#",
  text: "this is a test",
  click: function(e){
    e.preventDefault();
    alert(12);
  })
).append($("<br>"));
oomlaut
  • 763
  • 4
  • 12