使用sliderhow addClass removeClass jQuery问题

时间:2012-10-11 17:32:13

标签: jquery addclass next

以下是JSfiddle的链接。

使用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(它似乎很快添加/删除所有匹配的元素)。

我错过了什么?     

2 个答案:

答案 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

答案 1 :(得分: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);
}​

这是一个简化版本,删除了不相关的代码行。