If I have, for example, several <span>
and I click on one, how can I, with jquery, know which one I clicked on? Being the IDs of the elements automatically numbered with item_<?php echo $i; ?>
?
That is to say, I want that when doing in the span with id=item_2
it makes me, for example, a alert.()
"you have clicked on item_2"
<div id="items_en_uso">
<span style="background:#c9c9c9;padding:3px;" id="item_1">Hola</span><br><br>
<span style="background:#c9c9c9;padding:3px;" id="item_2">adios</span><br><br>
<span style="background:#c9c9c9;padding:3px;" id="item_3">buenas</span><br><br>
<span style="background:#c9c9c9;padding:3px;" id="item_4">malas</span><br><br>
</div>
EDIT:
Spans are added when clicking on another element with
$("#clikeable").click(function(){
$("#items_en_uso").append("<span id='item"+count+"'>Hola</span>");
});
If the spans are set by hand (not by jquery) it works, but if I add them with jquery when clicking on them, it doesn't work for me... How can I fix this?
jQuery's .click method only works on elements that are already in the DOM when the document loads. To bind events to elements added to the DOM dynamically, use the .on method on a containing element and filter by the selector of the element of interest.
Edit: As you comment, the code can be improved more.
This way you optimize the part where jQuery filters the event object element.
With this code you can do what you want, it simply listens for all span elements inside your
div
with id " items_in_use " in your code (preventing clicking on other span elements outside) and returns the value of the id attribute using the object$(this)
You can do this by referencing elements starting with that particular id (those starting with
item_
) with the selector^=
and then referencing the clicked element with the reserved wordthis
.In this way, once you have detected the element that has been clicked and that has an id that starts with
item_
, you will be able to obtain its attribute with its functionattr('id')
.I do the following to detect which element of a list is clicked, I hope it can help you.
You could use a selector for all elements of type span
In that case you would have to replace the span with the type of element you want to access.