0

这是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(它似乎非常快速地添加/删除所有匹配的元素)。

我错过了什么?​</p>

4

2 回答 2

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.

此处包含一些额外清理的完整示例

于 2012-10-11T17:37:47.977 回答
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);
}​

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

于 2012-10-11T17:44:07.240 回答