jqueryjquery-mobilejquery-mobile-listview

How do I get Index of Listview?


I can the correct index of listview using this code:

$('#listview').on('click', 'li', function() {
    alert( $(this).index());
});

This returns the correct index.

However if using this code, it always returns 0:

$('#listview').on('click', 'div', function() {
    alert( $(this).index());
});

I use second code to differentiate the click event among different divs.


Solution

  • The index gives you the position of the element relative to its siblings in the HTML tree. if your div is within the li and your HTML looks like this

    <ul id="listview">
       <li><div>First div for click handler</div></li>
       <li><div>Second div for click handler</div></li>
    </ul>
    

    Then 0 is the correct index for any div in the listview. Maybe you need something like this

    $(this).closest('li').index();
    

    in your click handler.