Does not show users name in Jquery alert

2

I want to access the text content inside the div and show it in an alert (), but for this I have a list of users selected from the database, I did a little trick to add a counter in each div class that contains the user name, see example:

and so on. But when I put the alert (), it displays all the users at once within the alert, even though I create a div for each one. Someone gives a help. my Code:

$('.innerbox_contatos_search').click(function(){
  $('.info-part a').addClass('ativo');
  var i = 1;
  $(".ativo").each( function() {
    $(this).attr("class", "ativo-"+i); 
    alert($('a.ativo-'+i).text());
  i++;
});
});
    
asked by anonymous 08.02.2015 / 20:16

2 answers

1

You do not need i++ to perform this operation. You do not need an accountant!

The each of jQuery uses this within the callback as the current element within the context of the loop.

See a modified example of your code:

$('.innerbox_contatos_search').click(function(){
    $('.info-part').find('a').addClass('ativo');

    $(".ativo").each(function() { 
      // this é o elemento atual do loop
      alert($(this).text())

  });
});

See working at JsFiddle

    
09.02.2015 / 15:47
0

This is because you are putting in alert the entire element. You need to use this to access the content of the element that was clicked. Try modifying your code for:

$('.innerbox_contatos_search').click(function(){
  $('.info-part a').addClass('ativo');
  var i = 1;
  $(".ativo").each( function() {
    var textAlert = "ativo-"+i;
    $(this).attr("class", textAlert); 
    alert($(this).text() + " " + textAlert);
    i++;
  });
});
    
09.11.2018 / 12:14