2017-05-03 33 views
0

我正在使用jQuery,並且想要在數組中存儲一個histed元素列表。我使用的代碼如下(你可以將其粘貼到一個空的HTML文檔進行測試):index一個jQuery對象總是返回-1

<div class="element" style="width:100px;height:100px;border:1px solid black;"></div> 
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> 
<script> 
var hovered = []; 
$(document).ready(function(){ 
    $(".element").hover(function(){ 
     hovered.push($(this)); 
     console.log(hovered.indexOf($(this))); 
    }); 
}); 
</script> 

每當我將鼠標懸停在DIV,-1總是被記錄到控制檯。爲什麼這是一個潛在的解決方法?

+2

因爲'{} === {} // false'兩個對象永遠不會相互等同。 –

+0

您正在構建兩個不同的對象。你推的那個和你要找的那個。 –

回答

0

將其更改爲

hovered.push(this) 

hovered.indexOf(this) 
+0

這是一個很好的解決方案嗎?他應該只使用'this'或者保留對創建的jQuery對象的引用,將其推入並在查找中使用它。 –

+0

是的,他確定他可以使用這個並保持dom元素 – quirimmo

-1

您將創建兩個不同的jQuery對象,一個你推,和一個你 通行證的indexOf(..)

更改您的代碼,如下所示:

$(document).ready(function(){ 
    $(".element").hover(function() { 
     var $this = $(this); 

     hovered.push($this); 

     console.log(hovered.indexOf($this)); 
    }); 
});