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.
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
});
$(".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/
var i = 0;
$(".portfolio-click").each(function(){
$(this).attr('index_number', i++);
});
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.