0

I have four divs where the first div has a class "selected". I would like to remove that class and append it to the next div number two after 2000 milliseconds. But then after another 2000 milliseconds i need that class to be removed and to be appended to the div number 3 and so on. But this does not work. any clues?

JavaScript

var sel = "";
function aaa() {
    $('#holder > div').each(function () {
        var isSelected = $(this).hasClass("selected");
        if (isSelected) {
            var selectedId = $(this).attr('id');
            console.log(selectedId);
            $(this).removeClass("selected");
            $("#" + selectedId).next().addClass("selected");
        }
    });
}

setInterval(aaa, 5000);

HTML

<div id="holder">
    <div id="one" class="selected"></div>
    <div id="two"></div>
    <div id="three"></div>
    <div id="four"></div>
</div>
4

3 回答 3

1

You mistyped "selected" on this line:

$(this).removeClass("selectedP");

Also, you can get to the selected div directly:

function aaa() {
  var $selected = $("#holder > .selected");
  var $next = $selected.next();

  // Wrap around
  if($next.length === 0) {
    $next = $("#holder > div:first-child");
  }

  $selected.removeClass("selected");
  $next.addClass("selected");
}
于 2013-11-07T17:06:50.547 回答
1

Using jQuery and inside the document.ready() function:

while(someConditionThatWillStopTheMadness)
{
    setInterval(moveToNextDiv, 2000);
}

function moveToNextDiv(){
    var currentDiv = $('#holder > div.selected').removeClass("selected");
    var nextDiv = currentDiv.next().addClass("selected");
}

Obviously someConditionThatWillStopTheMadness is just something that will stop this, for example a check that this is indeed the last div. You can loop back to the first one at that point or just stop the loop

于 2013-11-07T17:08:59.100 回答
1

Your error come from selectedP instead of selected

You can also simplify your come with something like :

  function aaa() {    
        var currentDiv = $('#holder .selected');
        currentDiv.removeClass("selected");
        currentDiv.next().addClass("selected");    
  }
于 2013-11-07T17:12:09.633 回答