开发者

Finding divs by 2

How to select divs with same id but to select them, like that the 1-3-5-7-9 only these divs to select.

I had tryed like that

$("document").ready(function(){
var c = $("#as").length;
for(var a  = 0; a<c;a--)
{

 if(c[a]%2==0){
     }
}
}); 

but it did开发者_运维知识库 not worked


To make the odd divs with a class of as, not id (since you should try to only have 1 element with a given id per page), have a background color of blue do this:

$(document).ready(function() {
  $('.as:odd').css('background-color','#0000FF');
});


You shouldn't have the same ID more than once in your markup. Use a class instead as IDs are supposed to be unique.

For the "every second" part you can use the :odd modifier in your selector:

$("#as:odd").each(function(elm){
  // Do something here with the element (elm)
});


You could use this construction:

$('div-selector:odd')


To find only the odd ones:

$('divSelector:odd').css('background-color','#ffa');

Will turn all the odd-numbered divs selected by the selector to a yellow-background.

The divSelector could be anything from a class-name $('.classNameOfDivs'), or simply the element-type: $('div').


To fix your code:

$(document).ready(function()
{
    var c = $("#as");
    for(var a = 0; a < c; a++)
    {
        if (a % 2 == 0)
        {
            var element = c.eq(a);

            // Do stuff here.
        }
    }
});

A better way, however, would be to use the :odd and :even selectors. Also note that you shouldn't have more than one element with the same id; use class instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜