I’m having trouble referencing the proper html elements with the javascript “this” reference using the “parent” method. Suppose my html is as follows:
<ul id="list" >
<li id="Template" >
<a href="#" >
<h3 class="Name" ></h3>
</a>
<a class="Link" ></a>
</li>
</ul>
Using jquery, I can dynamically create links out of the items in a list :
var jqXHR = $.getJSON( url, params, function(obj, status, xhr){
var obj = jQuery.parseJSON(xhr.responseText);
for (var i=0; i < obj.length; i++)
{
var newEntryRow = $('#Template').clone();
newEntryRow.removeAttr('id');
newEntryRow.data('userID', obj[i].id);
newEntryRow.appendTo('#list');
newEntryRow.find('.Name').text(obj[i].user_name);
newEntryRow.find('.Link').click(function(){
var clickedUser = $(this).parent();
var clickedUserID = clickedUser.data('userID');
});
}
The above code will assign an “id” to each link created in the list (0, 1, 2…); however, the jquery doesn’t work for the following html:
<ul id="list" >
<li id="Template" >
<a class="Link" >
<h3 class="Name" ></h3>
</a>
</li>
</ul>
The second html snippet also creates a list of 5 “Name” links; however, the jquery assigns an “undefined” (vs. a valid ID – 0, 1, 2, 3, 4) to each of the links created in the list. Can somebody tell me why the 2nd html snippet isn’t working and how I can modify the jquery code so that the links have a valid ID assigned (instead of an “undefined”)?
Thanks!
1 Answer