2015-07-02 149 views
0

請看:http://jsfiddle.net/dmhsfds4/jquery Index()無法正常工作?

主要指數給出-1所有的時間,即使是存在與.current類元素,當函數運行。

這是一個錯誤?

<p class="current" id="one">Point 1</p> 
<p id="two">Point 2</p> 
<p id="three">Point 3</p> 
<p id="four">Point 4</p> 
<p id="five">Point 5</p> 
<p id="six">Point 6</p> 
<p id="seven">Point 7</p> 

var p = $('p'); 
var i = 0; 
setInterval(function(){ 
    i +=1; 
    if (i>6) i=0; 

    console.log(p.index('.current')); 

    p.removeClass('current').eq(i).addClass('current'); 
},1000); 
+0

你的HTML是這個問題的一個組成部分。請將所有相關代碼直接放在問題中,而不是讓問題依賴於場外資源。 –

+1

這是jQuery API最糟糕的例子之一。這是完全不明確的,可以說是更直觀的方式來解釋它的含義。但jQuery只是喜歡用不同行爲重載方法。他們會更好地使用不同的命名方法,比如'element.getIndexIn(collection)'和'collection.indexOf(element)'。 –

回答

2

您需要更改p.index()$('p.current').index()p.index()只是檢查第一個p不是每一個。 這是fiddle

0

jQuery docs提到的,

功能.index()接受一個元素作爲像這樣的參數。

p.index($('.current')) 

類或ID這樣的。

p.index('.current') OR p.index('#someId')

這裏是更新fiddle

+1

文檔顯示它*不接受選擇器字符串,但是當您這樣做時,它的行爲會有所不同。 –