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.

有帮助吗?

解决方案 3

var i = 0;
$(".portfolio-click").each(function(){
    $(this).attr('index_number', i++);
});

其他提示

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;
});

FIDDLE

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 )

Fiddle Demo

$( ".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

Fiddle Demo

$(".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/

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top