Reputation: 353
How am I able to add a click event to this dynamic element and how to get the text of the clicked one?
$data.append("<tfoot><tr><td></td</tr></tfoot");
$("#tab2").html($data);
alert(data.n);
for (i = 0; i < data.n + 1; i++) {
thelink = $('<a>', {
text: i,
href: '#'
}).appendTo('tfoot');
}
Upvotes: 0
Views: 55
Reputation: 135862
The theLink
variable you create within the for
loop is a jQuery object (the result of the call to .appendTo()
is still the created link).
You can, as usual, call .click(<function>)
on it to bind a function to the click event.
Example:
$data.append("<tfoot><tr><td></td</tr></tfoot>"); // added > at the end of the string
$("#tab2").html($data);
alert(data.n)
for (var i = 0; i < data.n + 1; i++) { // added var before i
var thelink = $('<a>', { // added var before thelink
text: i,
href: '#'
}).appendTo('tfoot');
// Now you can add the click event:
thelink.click(function () {
alert("Hello, you clicked the link number "+i);
});
}
On a side note, maybe you should call .appendTo('#tab2 tfoot')
instead of just .appendTo('tfoot')
- the latter will add the link to all tfoot
s on the page, the former just to #tab2
's tfoot
.
Upvotes: 1