简体   繁体   English

单击并触发由Ajax生成的表上的函数

[英]Click and trigger a function on table generated by Ajax

My page has ajax function which generate table and attache it to a div. 我的页面具有ajax函数,可生成表并将其附加到div。 Following is the php page called by Ajax. 以下是Ajax调用的php页面。

echo "<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id='tablecat'>";

while ($row = mysql_fetch_assoc($results)) {
    $category = $row['category'];

echo "<tr bgcolor='white'>
<td class='value'>$category</td>
</tr>";
}

echo  "</table>";

Then I need to call another ajax call when the table cells are clicked. 然后,当单击表格单元格时,我需要调用另一个ajax调用。 Tried many ways but no success. 尝试了许多方法,但没有成功。

$("#tablecat").on("click", "td", function() {

});

Can someone tell me how to do this? 有人可以告诉我该怎么做吗? Thanks. 谢谢。

Your event delegation did't work in this case because $("#tablecat") also created dynamically, you need to reference on its top level like the div that hold the table or the body or document like so: 您的event delegation在这种情况下不起作用,因为$("#tablecat")也是动态创建的,因此您需要在其顶层引用,例如div来保存tablebodydocument如下所示:

$(document).on("click","#tablecat td", function() {
     alert('hi');
});

As I understand you write your event listener on document ready, but as listener setted to object which not exists on document ready (it gets by ajax) it does not work. 据我了解,您在文档准备就绪时编写了事件侦听器,但是由于侦听器设置为文档准备就绪不存在的对象(通过ajax获取),因此它不起作用。

You can set listener on body, for example: 您可以在主体上设置侦听器,例如:

$("body").on("click", "#tablecat tr td", function(e) {

});

I know one option, you can you the jQuery code inside AJAX success function. 我知道一个选择,您可以在AJAX成功函数中使用jQuery代码。 For an example: 例如:

$.ajax({
url: "/fielname.php", 
type: "POST", //POST
success:function(response) {
    $("#tablecat").on("click", "td", function() {

    });
},
error:function(data){

}

}); });

you just need to set 您只需要设置

$("#tablecat").on("click", "td", function() { 

});

in a function and when you generate table with ajax, on success - call this function. 在函数中,当您使用ajax生成表时,成功时-调用此函数。

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

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