简体   繁体   中英

Number elements by class and get placement of specific div

I have a list like this:

<div class="list"></div>
<div class="list"></div>
<div class="list on"></div>
<div class="list"></div>
... etc

I get the total like this:

var count = $('.list').length; // 4 in this case

But I want to write a function that selects the next div with the down arrow, and I can't figure out how to get the next div, select it, and deselect the current div. This is what I have now, but it doesn't work:

var visible = $('.list:visible');
var on = $('.list.on:visible');
if (e.keyCode == 40) { // down key
    if(on.length == 0) {
        visible.first().addClass("on"); // this works
    }
    else if( // div placement // < count) {
        var next = on.next(); // this part doesn't work
        on.removeClass("on"); // :(
        next.addClass("on"); // :(
    }
    else { // if its the last div
        // do nothing
    }
}

You can do:

if (e.keyCode == 40) { // down key
    if(on.length == 0) {
        visible.first().addClass("on");
    }
    else if(on.length && on.next("div.list").length > 0) {
        var next = on.next("div.list");
        on.removeClass("on");
        next.addClass("on");
    }
    else { // if its the last div
    // do nothing
    }
}

A quick demo: http://jsfiddle.net/GL7tA/

You can work with .index() to see which item is currently "selected":

var $items = $('.list:visible'),
$selectedItem = $items.filter('.on'),
selectedIndex = $items.index($selectedItem);

if (selectedIndex == -1) {
  $items.eq(0).addClass('on');
} else if (selectedIndex + 1 < $items.length) {
  $selectedItem.next().andSelf().toggleClass('on');
}

You have a syntax error in the else if ( part, where you say it doesn't work.

It doesn't work because the else if is expecting a condition to evaluate but you are not even closing the parenthesis of that if condition, neither have you openned the brackets for its block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM