views:

31

answers:

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  A: 

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();
Alex Sexton