Reputation: 877
i have a dynamically created list with data of a json. So my question is how to get the index of a clicked item.
I tried this:
$("li").click(function() {
var index = $("li").index(this);
alert(index); });
But this didnt work. I dont get an alert? If i create some static Li elements, i get the index of them.
Please help me :/
Upvotes: 0
Views: 698
Reputation: 826
Try the following. assuming that ul
is not loaded dynamicaly.
$("ul.containerclass").on("click", "li", function()
{
var index = $(this).index();
alert(index);
});
or
$(document).on("click", ".containerclass li", function() {
var index = $(this).index();
alert(index);
});
Note : here containerclass can be ID
Upvotes: 0
Reputation: 1075337
Two issues:
You just want $(this).index()
:
$("li").click(function() {
var index = $(this).index();
alert(index); });
From the documentation:
If no argument is passed to the
.index()
method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.
When you do $("li").click(...)
, it hooks it up to the elements that exist at that point in time. Ones you add later won't get the click handler assigned to them. The best way to approach dynamic lists like this is usually event delegation. DevlshOne gives you an example in his/her answer. The basic idea is this:
$("selector for the list, not the list items").on("click", "li", function() {
// handler code here
});
That hooks click
on the list, not the list items, but then fires the handler when the click occurs as though you had hooked click on the handler.
Upvotes: 1
Reputation: 8457
Dynamically created lists will require delegated events...
$("ul").on("click", "li", function() {
var index = $(this).index();
alert(index);
});
If the <ul>
is also dynamically created, please select a parent node that exists before the list is created.
Upvotes: 2
Reputation: 1585
It is
$("li").click(function() {
var index = $(this).index();
alert(index);
});
Upvotes: -1