简体   繁体   中英

Add Click Event to Dynamic Element

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

}

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM