0

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');

}

1 Answer 1

1

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 tfoots on the page, the former just to #tab2's tfoot.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.