【问题标题】:Click event not working on dynamic Id点击事件不适用于动态 ID
【发布时间】:2017-07-13 16:47:16
【问题描述】:

我正在创建一个动态表,并希望通过单击具有动态创建 ID 的 <a> 元素来显示一个表单。我能够显示表单的唯一方法是将点击事件中的选择器设置为表 ID(#table 2),但我不明白为什么我不能更具体地做到这一点。

$.each(json, function (index, value) {
    var posttimestamp = value.Post_timestamp;
    var replytimestamp = value.Reply_timestamp;
    var topic = value.Topic;
    var post_txt = value.Post_txt;
    var reply_txt = value.Reply_txt;
    var species = value.Species;
    var postuser = value.Post_User;
    var replyuser = value.Reply_User;
    var medcond = value.MedCondPrimary;
    var breed = value.Breed;

    if (value.Post_timestamp != check) {
        var newpost = 'y';
    } else {
        var oldpost = 'y';
    }


    if (newpost) {
        $('#table2').append('<tr><td   id="posttopic" colspan="2"><a href="forum24.php"           id=' + posttimestamp + '>' + topic + '</a></td><td></td></tr><tr><td id=' + "post" + posttimestamp + '>' + posttimestamp + '</td><td  id=' + "post" + posttimestamp + 'colspan="3">' + post_txt + '</td><td>' + postuser + '</td><td>' + breed + '</td></tr>');
    }

    $('#' + posttimestamp).click(function (e) {
        e.preventDefault();
        $('div.form').show();
    }

【问题讨论】:

  • 您的标记看起来如何? $('#'+ posttimestamp) 是什么,你能发一个小提琴来复制这个问题吗?

标签: javascript dynamic html-table click


【解决方案1】:

尝试改变它

$('#' + posttimestamp).click(function(e) {...})

$('#' + posttimestamp).live("click", function(e) {...})

您可能会遇到这样的情况,即 jQuery 试图将点击事件绑定到您的 .append()-ed 表格单元格,但该单元格在 DOM 中尚不存在。使用.live() 会将点击事件绑定到现在或将来存在的元素。

之所以使用表ID作为选择器,是因为当你调用.click()时,表肯定已经存在于DOM中了。

【讨论】:

  • 谢谢,这行得通。根据您的回答,我做了一些进一步的研究,发现从 jQuery 1.7 开始, .live() 方法已被弃用。使用 .on() 附加事件处理程序。我也尝试了 .on 方法,但没有奏效。奇怪,因为语法看起来和 .live 几乎一样。
【解决方案2】:

试试jQuery.live()

 $('#' + posttimestamp).live("click", function (e) {
     e.preventDefault();
     $('div.form').show();
 }

【讨论】:

    猜你喜欢
    • 2014-07-28
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2021-10-19
    相关资源
    最近更新 更多