If I have a structure like this:
<body>
<div data-role="page" data-dom-cache="true" id="foo">...</div>
<div data-role="page" data-dom-cache="true" id="bar">...</div>
<div data-role="page" data-dom-cache="true" id="baz">...</div>
</body>
How do I get the position of bar in this series of divs? It should return 2 in this case.
I’m using this to try to get the index of the current page in jquery mobile. Right now I’m doing:
$( '#<%=@page_id%>' ).bind( 'pageshow',function(event){
alert('current page = '+$.mobile.activePage.index())
})
But this is showing me index=1 for the 1st page, index=3 for the 2nd page and from there it increases linearly to 4,5…
Use
index():Which will return the index position of the element among its sibling elements, or you can pass a selector:
Wherein jQuery will return the index position of
$('#bar')among the matched elements returned by the selector passed to index.Note that JavaScript works with zero-based arrays; so the above (in the first) will return
1(not2). If you must have2then remember to explicitly+ 1:But, when using that
indexvariable (perhaps witheq()) remember to adjust for that addition, otherwise things may break unexpectedly. Or, at least, work differently.References:
index().