0

i have an unordered list with an unknown number of list items. it looks like this:

<ul id="keyvisualpager">
    <li><a><span>first</span></a></li>
    <li><a><span>second</span></a></li>
    <li><a><span>third</span></a></li>              
    <li><a><span>and so on</span></a></li>              
    <li><a><span>fsdfsf</span></a></li>             
    <li><a><span>asdad</span></a></li>              
</ul>

when the user clicks on a link, i need to find out the index of the list element and assign it to a variable. e.g. if the user is clicking the second link ("second") the variable should be set to "2"...

$('#keyvisualpager li a').click(function () { 

     // receive index of list element
     var mbr_index = ???;   


});

i have to use jquery 1.2.1 ... so no fancy stuff please :)

any help is greatly appreciated, thanks!

2 Answers 2

4

Maybe you overlooked that .index(element) [docs] was already available in jQuery 1.0:

var $items = $('#keyvisualpager li');

$items.find('a').click(function () { 
     var mbr_index = $items.index($(this).parent()) + 1; // one based index
});

Original answer:

This should work in jQuery 1.2:

var mbr_index = $(this).parent().prevAll().length + 1; // one based index
Sign up to request clarification or add additional context in comments.

Comments

1

You might consider assigning the click a little more manually using each(). You can iterate over the list items and have the index available to you. You can find the anchor within the list item and bind its click method.

$('#keyvisualpager li').each(function(index) {
    $(this).find('a').bind('click', function() {
        var mbr_index = index + 1; // indices start at 0
        ...
    });
});

each() was available in jQuery 1.0 so you should be able to use it no problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.