jQuery: getting the nth position of an object
I 开发者_JAVA百科have a div that contains checkboxes. I also have a function that accepts a jquery object parameter. It looks like this:
function analyze_checkbox(cb) { ... }
Given this, is there a straightforward way to know the child position of the cb parameter? I was thinking of something like this:
cb.parent().index(cb)
What is the proper way to do it?
Thanks,
Erwin
Quoting from .index()
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.
So in your case cb.index();
should do it
Example at http://www.jsfiddle.net/qQzte/
and do not forget that the results is 0-based
If your checkboxes really are siblings of each other, then Gaby's answer saying cb.index()
should do it is quite correct. Be careful, though, that you understand what index
is actually telling you. For example, with this markup:
<div id='thediv'>
<label><input type='checkbox' value='1' name='one'>One</label>
<label><input type='checkbox' value='2' name='two'>Two</label>
<label><input type='checkbox' value='3' name='three'>Three</label>
<label><input type='checkbox' value='4' name='four'>Four</label>
</div>
...if your cb
is from (say) $('#thediv input[type=checkbox][name=three]')
, the result of cb.index()
will be 0
(link to example). Clearly not what you want.
You can handle that in a couple of ways. With the specific example above, you could just look to see where the parent label
was relative to its siblings: cb.parent().index()
(link to example). But depending on your markup, that could be complicated.
There's a way that's less subceptible to subtle markup changes: Select exactly the list of elements you want to consider, and then ask jQuery where cb
is within that list. So with the markup above, you might do this:
// The selector choose *exactly* the set of things we want to
// look at, and then `index` looks for `cb` within that list
var index = $('#thediv input[type=checkbox]').index(cb);
link to example
精彩评论