Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append generated numeric ids to some links

I have generated numeric IDs to apply in list that looks like:

var _href = $('li').attr('id', function (i, _) {
    return 'item-' + (i + 1);
});

Now I want to put this IDs in some links, here is my code:

$("a").attr({
    href: "#item-" + _href
});

All I need is a multiple repeated list with id (li#item-1 , li#item-2 , ...) and some links with those IDs

But it's not working, the result is: #item-[object Object]

like image 507
DarkBlueS Avatar asked Jan 18 '26 20:01

DarkBlueS


1 Answers

You can do it simultaneously targeting an <a> using .eq(Index)
(where Index is the current LI's Index iteration)

var $a = $("a"); // P.S: use some better selector like i.e. $("#menu").find("a");

$('li').attr('id', function (i, _) {
   var id = "item-" + (i+1);            // Prepare the result
   $a.eq(i).attr("href", "#"+ id);      // Assign result with #HASH to Anchors .eq()
   return id;                           // Return result as ID
});

http://jsbin.com/joraja/1/edit?html,css,js,console,output


https://api.jquery.com/eq/

like image 126
Roko C. Buljan Avatar answered Jan 20 '26 12:01

Roko C. Buljan