简体   繁体   中英

How to iterate through jquery selection

I am trying to figure out how jquery selectors work when selecting a group of elements. Once i have the all of the elements i am trying to iterate through and check a style value of them to find which one has that and it does not seem to work. Do i have to iterate through them differently? Thank you for any help. I have tried searching and messing with it and this is what i have as of now.

function toggle() {
    //get all the content divs
    var $all_divs = $('.content_div');

    //find the content div that is visable
    var $active_index = -1;
    for (i = 0; i < $all_divs.length(); i++) {
        if ($all_divs[i].style.display == "block") {
            $active_index = i;
        }
    }

    $all_divs[$active_index].style.display = "none";
}

edit:

Some more info on where i am headed with this.

Basically i have 4 divs, and when i click a button i want the one that is visible to go away, and the next one in the list to appear.

Whole code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>

<style type="text/css">
.wrapper {
    width:450px;
    height:30px;
    position:relative;
}

.slide_button {
    width:25px;
    height:30px;
    position:absolute;
    top:0;
}

#left {
    left:0;
}

#right {
    left:425px;
}

.content_div {
    width:400px;
    height:30px;
    position:absolute;
    top:0;
    left:25px;
}
</style>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
function toggle() {
    var Divs = $('.content_div');
    var i;
    var index = 0;

    Divs.each(function(index) {
        if ($(this).css('display') == 'block')
            i = index;
        index++;
    });

    if(typeof i !== 'undefined'){
        Divs.eq(i).css('display', 'none');
    }
}
</script>


</head>

<body>
<div class="wrapper">
    <div class="slide_button" id="left">
        <center><a href='javascript:toggle();'><</a></center>
    </div>
    <div id='div1' class='content_div' style="display:block;">
        this is div 1
    </div>
    <div id='div2' class='content_div' style="display:none;">
        this is div 2
    </div>
    <div id='div3' class='content_div' style="display:none;">
        this is div 3
    </div>
    <div class="slide_button" id='right'>
        <center>></center>
    </div>
</div>
</body>
</html>

I think the reason your code doesn't work is the use of .length() in the for loop condition. jQuery objects don't have a .length() method, they have a .length property. Drop the brackets and your code should work.

EDIT: For your requirement to display the divs one at a time you can do something like this:

$(document).ready(function() {
   var $divs = $("div.content_div").hide(),  // first hide all the divs
       i = 0;    
   $divs.eq(i).show();                       // then show the first

   $(".slide_button a").click(function() {        
       $divs.eq(i).hide();                   // on click hide the current div
       i = (i+1) % $divs.length;             // then update the index to
       $divs.eq(i).show();                   // show the next one
   });
});

Demo: http://jsfiddle.net/7CcMh/

(The rest of my original answer:) The syntax you are using to access the individual elements is OK: if $all_divs is a jQuery object, which it is, then $all_divs[0] is a reference to the first DOM element in the jQuery object. However, jQuery provides the .each() method to make this process easier:

$('.content_div').each(function() {
     // here 'this' is the current DOM element, so:
     if (this.style.display == "block")
         this.style.display = "none";
     // OR, to access the current element through jQuery methods:
     $(this).css("display", "none");
});

Having said that, it seems you expect all but one element to be hidden already and you are finding that one and hiding it too. If so, you can achieve that in one line:

 $('.content_div').hide();
 // OR
 $('.content_div').css("display", "none");

jQuery methods like .hide() and .css() apply to all elements in the jQuery object they're called on.

You can use jQuery each() method which lets you iterate through the selected elements.

$('.content_div').each(functon(index){
    if ($(this).is(':visible')) { 
        $(this).hide()
    } 
})

If you want to select the visible divs you can use the :visible selector:

Selects all elements that are visible.

$('.content_div:visible').css('display', 'none'): // or $('.content_div:visible').hide()

update:

you can add a class to the anchor and try the following:

<center><a href='#' class="toggle">></a></center>

$('.toggle').click(function(e){
  e.preventDefault()  
  if ($('.content_div:visible').next('.content_div').length != 0) {    
     $('.content_div:visible').hide().next('.content_div:hidden:first').show()
  } else {
       $('.content_div').hide().eq(0).show()
  }    
})

Demo

Use the standard each method from JQuery.

$('.content_div').each(function(index) {
    // do work with the given index
    if (this.style.display == "block") {
        this.style.display = "none";
    }
});

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