2009-10-28 37 views
1

我在.hover()函數中使用.index()時遇到了一些問題。謝謝你的幫助。在懸停中使用.index()

$("#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() { 
     } 
    ); 

如果它的確與衆不同,這是我使用的.log()函數的代碼:

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

:編輯:每評論,下面是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> 
+0

您可以添加HTML PLZ? – jantimon 2009-10-28 17:05:31

+0

肯定Ghommey - 謝謝你的迴應。我已經添加了html - 查看我的編輯 「:編輯:根據評論,這裏是html:」 – thinksketchdesign 2009-11-11 19:09:55

回答

1

通常jQuery的api是鏈接的東西。這意味着在通常情況下,在原生jQuery函數或插件的末尾,它會自行返回。 (通過return this;)。這就是允許jQuery使用鏈接的原因。由於前一個函數返回原始對象,因此您在鏈中運行的下一個函數是也是在原始對象上運行。

$.index()函數的情況下,它返回一個值。該值是一個表示其索引的整數。在本地整數上沒有log()函數。如果前面的函數返回可以調用下一個函數的值的類型,則會發生可鏈接性。 (例如"string".substring(1).indexOf('i')

在你的代碼可能會做:

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

$myUL.get(foo).log();