2012-10-11 54 views
0

以下是指向JSfiddle的鏈接。addClass removeClass滑動條顯示的jQuery問題

的Javascript:

var headerCount; 
var timeDelay; 
$(document).ready(function() { 
    headerCount = $('.headerlink').length; 
    timeDelay = $('.current').attr('ref'); 
    if (undefined != timeDelay) { 
    timeDelay = "5000" 
    } 
    setTimeout("advance()", timeDelay); 
}); 

function advance() { 
    $('.current').next('.headerlink').addClass('current2'); 
    $('.current').removeClass("current"); 
    $('.current2').addClass('current').removeClass('current2'); 
    if (headerCount == $(".current").index('.headerlink')) { 
    $('.current').removeClass('current'); 
    $('.headerlink:nth-child(1)').addClass('current'); 
    } 
    timeDelay = $('.current').attr('ref'); 
    if (undefined != timeDelay) { 
    timeDelay = "5000" 
    } 
    setTimeout("advance()", timeDelay); 
}​ 

HTML:

<a ref="5000" class="headerlink current" href="http://www.raceramps.com/12-4thqtr-twenty-five-dollar-rebate.aspx"> <img class="headerimg" src="http://www.raceramps.com/images/promos/4thQTR[25_rebateCheck].jpg" /> </a> 

<a class="headerlink" href="http://www.raceramps.com/2012-3rdqtr-25-visa.aspx"> <img class="headerimg" src="http://www.raceramps.com/images/promos/3rdQTR[25VISA_rebate].jpg" /> </a> 

<a class="headerlink" href="http://www.raceramps.com/12-4thqtr-twenty-five-dollar-rebate.aspx"> <img class="headerimg" src="http://www.raceramps.com/images/promos/4thQTR[25_rebateCheck].jpg" /> </a> 

<a class="headerlink" href="http://www.raceramps.com/12-4thqtr-twenty-five-dollar-rebate.aspx"> <img class="headerimg" src="http://www.raceramps.com/images/promos/4thQTR[25_rebateCheck].jpg" /> </a> 

問題:我們的目標是使代碼.current添加到next('.headerlink'),然後從原始刪除.current。但由於某種原因,它只是刪除.current(它似乎很快就添加/刪除所有匹配元素)。

我錯過了什麼?

回答

0

這確實作業全例如:

http://jsfiddle.net/carlosmartinezt/Erw8y/29/

的代碼如下:

$(document).ready(function() { 
    setTimeout("advance()", $('.current').attr('ref') || 1000); 
}); 

function advance() { 
    var nextHeaderLink = $('.current').removeClass("current").next('.headerlink'); 

    if(nextHeaderLink.length == 0) 
     nextHeaderLink = $('.headerlink:first-child'); 

    nextHeaderLink.addClass('current'); 

    setTimeout("advance()", nextHeaderLink.attr('ref') || 1000); 
}​ 

它是一個簡化的版本,去除不相干代碼行。

+0

請在您的答案中直接包含相關代碼,理想情況下對所做更改進行一些說明。如果jsfiddle無法訪問,這個答案應該保持相關。 –

+0

當然,我會這樣做 –

0

我相信你的意思有:

undefined == timeDelay 

,而不是!=

您正在通過undefined作爲setTimeout的持續時間,導致它立即執行。


您還可以簡化代碼並刪除不需要current2在一起。

var $current = $('.current'); 
var $newCurrent = $current.next('.headerlink').addClass('current'); 

$current.removeClass('current'); // This still only has the first element even though you added .current to another 

訣竅是變量$current包含與其創建時匹配其選擇器的元素。對DOM的後續更改不會影響$current中匹配元素的集合。

與一些額外的清理here

+0

任何關心評論爲什麼這得到downvoted? –