Add a sequence of numbers to divs
I have a list of 8 divs and need to add a sequence of cl开发者_如何学运维ass numbers to them using Jquery to style them individually. Need to add them to the 'content-block' div see example below.
The desired effect will be something like this:
<div class="wrapper">
<div id="content-block" *class="post1"*>
</div></div>
<div class="wrapper">
<div id="content-block" *class="post2"*>
</div></div>
I have added the script
**Javascript**
$('.post-block').each(function(i){
$(this).addClass('post' + i);})
but I need to link them with anchor links so I will need a way to add an ID to the post-block.
Desired effect
**HTML**
<div id="post1" class="post-block">
</div>
<div id="post2" class="post-block">
</div>
Many thanks
jsFiddle example
First, you can only use an ID once on a page. You can use classes many times on a page.
Because of this I made content-block
a class, and I made your various post1
, post2
... ids.
The function below will go through each of the elements that have the content-block
class within a wrapper
class, and it will add an appropriate id
to each one. For the callback function of each()
you can make use of the index
and value
as arguments. I created a separate num
variable, since index
starts at zero.
In the each
function, you could also use this
instead of value
.
The jQuery:
$.each($(".wrapper > .content-block"), function(index, value){
var num = index + 1;
$(value).attr("id","post"+ num);
});
You can use this:
$(".content-block").each(function(i){
$(this).addClass("post" + i);
})
Obs: I'm using class selector (".content-block") not id selector ("#content-block").
If you get rid of the IDs, you could simply do this (assuming there's only one child <div>
per .wrapper
.
$(".wrapper > div").addClass(function(i) { return 'post' + (i + 1) });
This will result in:
<div class="wrapper">
<div class="post1"></div>
</div>
<div class="wrapper">
<div class="post2"></div>
</div>
<div class="wrapper">
<div class="post3"></div>
</div>
...
You are probably confusing unique CSS IDs with classes, which are normally used to give elements a common look and feel. Here's how you would assign unique IDs to all elements within your markup:
$('.wrapper').find('div').each(function(index){
$(this).attr('id', 'unique-' + ++index);
});
Let's assume you fix the duplicated id
problem, and you have an outer container object. Then we'd have:
$('div#outercontainer').find('div.wrapper > div').each( function(i){
var postnum = i+1; // remove any possible overloaded "+" operator ambiguity
$(this).addClass('post'+postnum);
});
Why not turn your divs into li, part of a OL element? Semantically more relevant...
精彩评论