2016-03-03 81 views
1

我有兩個列表。我正在獲取鼠標懸停的列表項索引。例如A有0個索引。 B有1個index..But我想換句話說添加指標,如果用戶將鼠標懸停在第二個列表A。它使輸出9不是0 ..如何在鼠標懸停的事件上添加索引?

我在第二列表第一次得到0 ..我想將它添加如果用戶將鼠標懸停在第二個列表上,則爲第一列表的長度

這裏是我的代碼使用$(selector).index()只是姐弟指標的index() https://jsfiddle.net/e46atunm/1/

$(function() { 
    $('#main-menu li').on({ 
    mouseenter: function() { 
     console.log("mouse over: " + $(this).index()) 
    }, 
    mouseleave: function() { 
     console.log("mouse leave: " + $(this).index()) 
    } 
    }); 
}) 
+1

請把所有相關的HTML中的問題本身。問題應該是自包含的,所以整個問題是清楚的,不必離開現場 – charlietfl

+0

請參閱我的純[CSS解決方案]的答案(http://stackoverflow.com/a/35780038/2813224)。 – zer00ne

回答

1

簡單的情形。

您也可以集合中的索引定義使用$(collectionSelector).index(element)

var $li = $('#main-menu li').on({ 
    mouseenter: function() { 
     console.log("mouse over: " + $li.index(this)) 
    }, 
    mouseleave: function() { 
     console.log("mouse leave: " + $li.index(this)) 
    } 
    }); 

DEMO

+0

沒有得到正確的輸出 – user944513

+1

然後什麼是預期的結果。適用於我,當我追加值https://jsfiddle.net/e46atunm/4/ – charlietfl

0

我覺得這可能是工作

$(function() { 
    $('#main-menu li').on({ 
    mouseenter: function() { 
     var before = $(this).parents('section').prevAll().find('li').length; 
     console.log("mouse over: ", before+$(this).index()); 
    }, 
    mouseleave: function() { 
     var before = $(this).parents('section').prevAll().find('li').length; 
     console.log("mouse leave: ", before+$(this).index()); 
    } 
    }); 
}) 
相關問題