user2031201 user2031201 - 1 year ago 43
Javascript Question

jQuery selectors after dynamic reload, and $(this)

I need some help. I load a list of entries in a div every 5 seconds. Each entry is a div and has a unique ID. Like this:

<div class="entry">
<div class="textbox">
<p class="entry-text">
<?php echo $text;?>
<div class="infobox">
<p class="date"><a #<?php echo $id;?> id="<?php echo $id;?>" href="gen_details.php?id=<?php echo $id;?>"><?php echo $t;?></a> </p>
<p class="ip"><?php echo $ip;?></p>

These, as I said are loaded each 5 seconds. I'm adding a details page for every entry, with this:

$('.date a').click(function () {
var dataString = 'id=' + $(this).attr("id");
type: "POST",
url: "gen_details.php",
data: dataString,
success: function(data) {
refresh = 0;
return false;

This works perfectly fine, until it reloads. It seems to lose the handle for the a href and instead of doing the procedure it goes to gen_details.php

I have tried to use .on() but I don't know how would I get the ID of the entry using .on(), as I cant use $(this) (afaik).

I hope I explained my problem at least half-well. English is not my first language so it wasn't that easy.

Thanks in advance.


Try this selector

$('div').on('click', '.date a', function () {

This will delegate the event to its parent div. So it should work for dynamically created elements as well.