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]
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With