简体   繁体   English

jQuery onClick自动生成的表不起作用

[英]JQuery onClick auto-generated table not working

I am auto populating a table from JSON data that a retrieve via $.getJSON. 我正在自动通过$ .getJSON检索的JSON数据填充表格。 call. 呼叫。

when i click ant i want to show an alert. 当我单击蚂蚁时,我想显示一个警报。

this is my code. 这是我的代码。

<body>
    <div id="container">

        <div id="header">
            <img id="titleimage" border="0" src="images/title.png">
        </div>

        <div id="sub-container">
            <div id ="video_container">
                <h1>HTML5 local video file player example</h1>
                <div id="message"></div>
                <input type="file" accept="video/*"/>
                <video id="match_video" controls autoplay></video>
            </div>
            <div id="log_container">
                <table id="chart"class="masterTooltip" title="RaboPro12 League Table">
                    <tr>
                        <th>Time</th>
                        <th>Event</th>
                        <th>Name</th>
                    </tr>
                </table>
            </div>
            <div id="stats_container"></div>
        </div>

    </div>
</body>

JQuery jQuery查询

$(document).ready(function() {

$.getJSON("php/getLog.php", function(result) {
    //var data = $.parseJSON(result);

    $.each(result, function(i, obj) {
        var fname = obj.first_name;
        var sname = obj.surname;
        var allName = fname + " " + sname;
        var time = obj.time;
        var event = obj.event;
        $('<tr id ="row"></tr').html('<td>' + time + '</td><td>' + event + '</td><td>' + allName + '</td>)').appendTo('#chart');
    });
}); 

$('.row').click(function() {
    alert("row clicked");
});

}); });

here is snippet of html after tableis populated. 这是表格填充后的html片段。

在此处输入图片说明

the row click is not triggered for some reason. 由于某些原因未触发行点击。

thanks 谢谢

All of your rows have an ID of "row" yet you are targeting a class of "row" in your jQuery. 您所有行的ID均为“行”,但您的目标是jQuery中的“行”类。 Change the IDs to classes and it will work. 将ID更改为class,它将起作用。

You need to use event delegation because when the event handler is registered all the target elements are not there in the dom, some of them are created dynamically. 您需要使用事件委托,因为在注册事件处理程序时,dom中不存在所有目标元素,其中一些是动态创建的。

$(document).on('click', '.row', function () {
    alert("row clicked");
});

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

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