I’m trying to assign a id to each link in my list like this,
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
$('#citations').append('<li><a href="' + link + '" id="num" + j>' +
json[j].title + '</a></li>');
alert($('a').attr('id'));
}
it keeps giving me undefined or 0? Should I use $.each outside of the for loop instead?
I was trying to use the for loop for two purposes but maybe that’s not such a great idea?
*EDIT***
If I put my for loop inside of a function like,
// Loop function for each section
var loopSection = function(start, stop) {
// Http setup for all links
var linkBase = "http://www.sciencebase.gov/catalog/item/";
// Link for citation information
var link = "";
for (var j = start; j < stop; j++) {
link = linkBase + json[j].relatedItemId;
var $anchor = $("<a>", {
href: link,
id: "id" + j,
text: json[j].title
})
// .parent() will get the <li> that was just created and append to the first citation
element
$anchor.appendTo("<li>").parent().appendTo("#citations");
}
}
I’m not able to access the id from outside of the function
$('#citations').on('click', function (e) {
e.preventDefault();
var print = ($(this).attr('id'));
alert(print);
});
This form is much cleaner:
If you want a reference to the anchor tag you created, do this: