Jump to content

index of in jQuery


williamrouse

Recommended Posts

Sorry about that!

Given the above structure of the div:

$(document).ready(function() {
               // put all your jQuery goodness in here.
               $('#mainMenu a').click(function(){
                   var $target = $(this).attr('id');
                   var $number = $(this).index('a');
                   $number++;
                   $("#response").text("Menu choice '" + $target + "' was chosen, OK! " );
                   $('#response').append('
That is item "' + $number + '".');
               });
           });

Link to comment
Share on other sites

It might work your way but I usually do it in the following syntax :P :

 

$(document).ready(function() {

// put all your jQuery goodness in here.

$('#mainMenu a').click(function(){

var $target = $(this).attr('id');

var $number = $("a").index(this);

$number++;

$("#response").text("Menu choice '" + $target + "' was chosen, OK! " );

$('#response').append('

That is item "' + $number + '".');

});

});

Link to comment
Share on other sites

BeeDev:

I'm not sure of your usage of "might" since it consistently works with the limited testing I have done. I wanted to ask though if you have been able to find your way through a returned object as I was trying to do too further understand JavaScript and jQuery. Here is what I mean more clearly, I hope:

$chosen = $('mainMenu a').click(function(){
});

Have you ever used that construct and then grab the ID name and index from the returned object?

Thanks now!

WBR

Link to comment
Share on other sites

Not really, you need to be inside some context to use index() because you need "this" to index something.

 

What are you trying to do? Maybe I know a different way to do it. Have you looked at .each() method?

 

You can do counters & stuff with it easily:

 

$("mainMenu a").each(function(counter){
   $(this).bind("click",function(){
       //you can use variable 'counter' here to program stuff like:
       $("#content div").eq(counter).show();
       //so when 4th link in main menu is clicked - the above script will show the 4th div inside element with id #content
   });
});

Edited by BeeDev
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...