1

I'm having some trouble with using the .index() inside of a .hover() function. Thanks for any help.

    $("#myUL li").hover(    
        function () {

            //this logs a li element as it should
            $(this).log();

            //this reports that it's not a valid function, why?
            $("#myUL").index(this).log();

            //when i do it this way...
            var foo = $("#myUL").index(this);
            //this returns -1.  Why can't it find the li?
            $(foo).log();

        },
        function () {
        }
    );

If it makes a difference, this is the code I'm using for the .log() function:

jQuery.fn.log = function (msg) {
    console.log("%s: %o", msg, this);
return this;
};

:edit: per the comment, here is the html:

    <ul id="myUL">
      <li>
        <div><img src="images/img1.jpg"/></div>
      </li>
      <li>
        <div><img src="images/img2.jpg"/></div>
      </li>
      <li>
        <div><img src="images/img3.jpg"/></div>
      </li>
    </ul>
1
  • sure Ghommey - thanks for the response. I have added the html - see my edit above ":edit: per the comment, here is the html:" Commented Nov 11, 2009 at 19:09

1 Answer 1

1

Normally the api of jQuery is to chain things. That means that in the usual case, at the end of a native jQuery function or plugin, it returns itself. ( via return this; ). This is what allows jQuery to use chaining. Since the previous function returns the original object, the next function that you run in the chain is also run on the original object.

In the case of the $.index() function, it returns a value. That value is an integer that represents its index. There is no log() function on a native integer. Chainability occurs when the preceding function returns the type of value that can have the next function invoked on it. (e.g. "string".substring(1).indexOf('i'))

In your code you might do:

var $myUL = $("#myUL"),
    foo   = $myUL.index(this);

$myUL.get(foo).log();
Sign up to request clarification or add additional context in comments.

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.