0

I have a problem - I put a piece of html code on the page using jQuery Ajax

example code:

<ul id="income">
<li id="1"><p>a1</p></li>
<li id="2"><p>a2</p></li>
<li id="3"><p>a3</p></li>
</ul>

I would like to know which element (id) was clicked by the user. Unfortunately, the following code does not work :(

$('li').click(function(){
   var info = $(this).attr('id');
   alert(info);
});

It seems to me that the problem stems from serving html with ajax. jQuery can not see it?

Pawciok
  • 21
  • 1
  • Using Ajax?? So those are dynamically created. They do not exist when the script is parsed. – Louys Patrice Bessette Jan 05 '18 at 23:35
  • If you are not going to use any other of the jQuery methods on the element, and you already have the element, there isn't a need to use the `attr()` method. `this.id` returns the same thing with two less method calls. – Taplar Jan 05 '18 at 23:40

2 Answers2

1

Your JavaScript snippet can be read as "find all list-items, and attach an event listener to each". Any list-items not in the DOM at the time your script runs will not have the event listener attached.

This can be done by attaching your event listener to an element that is in the DOM via delegation (click events on the list-items will bubble up the their parents)

Try this instead:

$('body').on('click', 'li', function(){
    var info = $(this).attr('id');
    alert(info);
});
Aaron Cicali
  • 1,496
  • 13
  • 24
  • Thank you very much :) The code works. I also understand what caused my mistake. – Pawciok Jan 05 '18 at 23:41
  • You shouldn't be doing the generally. Waiting for events to bubble up to the body before capturing the event can be really bad on performance. – Erik Philips Jan 05 '18 at 23:51
0

You can use one of this 2 approaches:

First:

$(document).on('click', 'li', function(){
  var info = $(this).attr('id');
  console.log(info);// or use alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="income">
  <li id="1"><p>a1</p></li>
  <li id="2"><p>a2</p></li>
  <li id="3"><p>a3</p></li>
</ul>

Second: (Using index in that case if your list element becomes too heavy and you cant set numbers of ids to them.)

$(document).on('click', 'li', function(){
  var info = $(this).index();
      info = info  + 1; // because index in JS is 0 base
  console.log($id);// or use alert
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="income">
  <li id="1"><p>a1</p></li>
  <li id="2"><p>a2</p></li>
  <li id="3"><p>a3</p></li>
</ul>
Colin Cline
  • 1,291
  • 1
  • 12
  • 25