开发者

The correct way of using jQuery index() ; ? Its always returning -1

Not sure why this 开发者_开发知识库is happening. But everytime I do (elem).index(); , it always returns -1 . Why is that?

How can I find the index of an object?


From the jQuery.index() documentation, among a lot of examples:

Return Values

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.

If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.

If a selector string is passed as an argument, .index() returns an integer indicating the position of the original element relative to the elements matched by the selector. If the element is not found, .index() will return -1.

Note the last sentence. Apparently elem is simply not found. Verify your selector and/or the element.


Update as per the comments, you're likely calling it at the wrong moment. Here's an SSCCE, copy'n'paste'n'run it.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 3740385</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            alert('Before DOM ready: ' + $(".nav ul li:first").index()); // Can return -1.

            $(document).ready(function() {
                alert('After DOM ready: ' + $(".nav ul li:first").index()); // Must return 0.
            });
        </script>
    </head>
    <body>
        <div class="nav">
            <ul>
                <li>item</li>
                <li>item</li>
                <li>item</li>
            </ul>
        </div>
    </body>
</html>

See also:

  • jQuery.ready() documentation
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜