简体   繁体   English

将点击事件添加到动态元素

[英]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). 您在for循环中创建的theLink变量是一个jQuery对象( .appendTo()的调用结果仍然是创建的链接)。

You can, as usual, call .click(<function>) on it to bind a function to the click event. 您可以像往常一样在其上调用.click(<function>)以将函数绑定到click事件。

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 . 附带一提,也许您应该调用.appendTo('#tab2 tfoot')而不是.appendTo('tfoot') -后者会将链接添加到页面上的所有tfoot ,前者仅添加到#tab2 ' tfoot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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