[SOLVED] get an attribute from a dynamically added element?
I've only recently started to learn jQuery. I'd like to use Ajax to get data from a server and populate the result with links that ultimately interact with a PHP updater to edit said data. I am stumbling over how to pass the ID# received from the server back through jQuery.
I've broken everything down into baby steps and this is the one I can't get past:
-
// Load the database results from content.php into div id="content"
$(document).ready(function() {
$("#content").load("content.php", addLinks);
});
// content.php provides a series of divs whose id = the unique identifier,
// e.g. <?php echo '<div id="key_' . $results['primary_key'] . ">...' ?>
function addLinks() {
$("div[id^=\'key_\']").each(function (i) {
var key = this.id;
$(this).append("<a id=\'key_" + key +"\'>test " + key + "</a>");
});// This part works!
$("#content").click(function(event) {
var $tgt = $(event.target);
if ($tgt.is(\'a\')) {
alert("Clicked a link: " + $tgt.id); // Identifies anchor clicks but $tgt.id is 'undefined' -- help!
} else {
alert("Not a link!");
}
});
}
I took my cues from
this tutorial and tried to adapt the principles to my needs. As noted, the $(event.target) doesn't seem to have an id. I've tried everything I can think of (e.g. var $tgt = $(event.target).id) but I sense I'm missing something fundamental here.
Any help would be much appreciated!