var i = 0;
$(".portfolio-click").each(function(){
$(this).attr('index_number', i++);
});
jQuery add index numbering to a class
-
15-10-2022 - |
Question
I have a lot of links on my website, all with the class "portfolio-click". I now want to add a "index number" to them all, so it would look something like:
<a class="portfolio-click" index_number="1">...</a>
<a class="portfolio-click" index_number="2">...</a>
Is there an easy way to make jQuery do this, so i can move around the links without interfering with the index order?
I tried:
$( ".portfolio-click" ).attr( "index_number", function() {
for (var i = 0; i < max_portfolio_number; i++) {
return i;
}
});
but that did not work.
La solution 3
Autres conseils
Not sure why you'd need it, but using a valid data attribute you could do this :
$( ".portfolio-click" ).attr( "data-index", function(i) {
return i;
});
You can always access elements by index with jQuery methods, as in
$( ".portfolio-click" ).eq(4); // gets the fifth (zero based)
so you don't need an attribute for that ?
You can use .each()
$(".portfolio-click" ).each(function(i) {
$(this).attr("index-number",i);
});
Use .attr( attributeName, value )
$( ".portfolio-click" ).attr( "index_number", function(i) {
return ++i; //index starts from so add 1 to it before return
});
Better use .data for custom attribute
$(".portfolio-click").attr("data-index_number", function (i) {
return ++i;
});
You can use jQuery's .each()
function:
$('a.portfolio-click').each(function(i) {
$(this).attr("index-number",i);
});
Preview: http://jsfiddle.net/rSGML/1/
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow