papelucho
papelucho

Reputation: 367

jquery .on() from append

I'm really confuse about how to add a click event to element created by jquery.

Now, I generate elements like this:

$.ajax(
    params....
)
.done(function(item){
    $.each(item, function(i, some){
        a = '<p>some text</p>';
        $(node).before(a);
    }
});

my problem is when I try to add a click event to element "p". If I do:

$('p').on('click', 'p', function(){
    alert('yai!');
});

Is showing nothing. BUt if I do:

$.ajax(
    params....
)
.done(function(item){
    $.each(item, function(i, some){
        a = '<p>some text</p>';
        $(a).click(function(){
            alert('yai!');
        });
        $(node).before(a);
    }
});

It show too many alerts (the same number of p elements)

What I'm doing wrong?

Upvotes: 4

Views: 130

Answers (2)

krishwader
krishwader

Reputation: 11371

Your options:

  1. (recommended) You could bind that click event on on the parent element. This is the best method because irrespective of the number of p inside its the parent the click is always attached to the parent and that makes it DRY and more performant.

    $("YourParentElement").on('click', 'p', function(){
       alert('yai!');
    });
    
  2. You could place your event handler with $("p") as selector after the $.each loop. At that time your p elements would be in DOM and so you can bind the click handler to the element. (Disadvantage : You'd be attaching the click handler to every single p, which is sometimes an overhead if you have a large number of similar ps)

    $.ajax(
      params....
    ).done(function(item){
       $.each(item, function(i, some){
           a = '<p>some text</p>';   
           // Click() was here causing it ////////
           //  to loop multiple times           //
           $(node).before(a);                   //
       }); ///////////////////////////////////////
           //
         / / / moved here
        $("p").click(function(){
            alert('yai!');
        });
     });
    
  3. You could bind this element (p) to the document object which always exists, even before jquery is loaded. And its not there now in the API. Going in those lines, it definitely not better to use live. For info on why live is evil, go here and here.

Upvotes: 4

Prashant
Prashant

Reputation: 702

I think you need to try below code to bind click event to paragraph tag.

$("p").click(function(){
    alert("clicked");
});

Hope this will help you.

Upvotes: 0

Related Questions