Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .each() to add event handler

I'm having an issue with the .each() function in jQuery, I'm calling these lines when I successfully getAjax and store it in the data variable:

$.each(data, function() {
$('#modulesList').append("<p><a href='#'>" + this.code + "</a></p>")
  .click(function(){
    alert($(this));
   });
});

The problem is, Once I click on one of my a elements(Which all look fine and have the correct text) I get the alert popping up 5 times for each of them. Iterating from the 0 to 5 objects in the JSON.

Anybody know why?

Thanks!

like image 243
Rich Avatar asked Jun 06 '26 17:06

Rich


1 Answers

Use the appendTo method

$("<p><a href='#'>" + this.code + "</a></p>").appendTo('#modulesList')
  .click(function(){
    alert($(this));
   })

jQuery ~ always returns the main element: now you selector is a dom element and this gets created and returned as a jQuery Object.

And to answer you question of why you get 5 alerts . Before you bound the click event to #modulesList one for each object in the data array. (Thats why the 5 alerts)

You can also store your <p><a>... in a variable like so:

var pAndATag = $("<p><a href='#'>" + this.code + "</a></p>");
$(modulesList).append(pAndATag);

hope you see how this works...

like image 50
Andreas Louv Avatar answered Jun 08 '26 09:06

Andreas Louv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!