jQuery DataTable-点击获取最接近td元素的类

jQuery DataTable - Get class of closest td element on click

本文关键字:td 元素 最接近 获取 DataTable- jQuery      更新时间:2023-09-26

给定一个jQuery数据表,如何确定是否在某一列上发生了单击?

我有一个jQueryDataTable实例,它填充了各种数据,这些数据是数据库记录的摘要。目前,单击一行会打开一个对话框,其中包含相应数据库记录的所有字段。如果单击的列有指定的类"comments",我想打开第二个对话框

目前,我通过初始化数据表

timelineTable = $("#timeline_table").dataTable({
    "aLengthMenu" : [
        ["-1", "10", "25", "50", "100"],
        ["All", "10", "25", "50", "100"]
    ],
    "iDisplayLength" : -1,
    "aoColumnDefs" : [
        {"bVisible" : false, "aTargets" : [6, 8] },
        {"sClass" : "comments", "aTargets" : [7]} //adds class 'comments' to this column index
    ]
});

并将点击事件绑定到动态填充的行:

$("#timeline_table").on("click", "tbody tr", timelineTableClickHandler);

这对于打开详细信息对话框的默认操作来说很好,但我想将函数处理程序修改为

$("#timeline_table").on("click", "tbody tr", function(e){
  if ($(this).closest("td").hasClass("comments")) 
    //call secondary dialog open event
  else
    //call default dialog open event
});

然而,$(this).closest("td").hasClass("comments")返回未定义,当我在Firebug中设置断点时,以下命令和输出结果

$(this).attr("id") prints out row id
$(this).closest("td") prints out jQuery( )
$(this).closest("td").text() prints out "", should be 0

这里的问题是this指向tr,因为您知道tdtr的子级,所以您不能在this上使用.closest()来查找单击的td

相反,您可以使用eventtarget属性来查找事件的实际源,并查找该元素的closesttd

$("#timeline_table").on("click", "tbody tr", function(e){
  if ($(e.target).closest("td").hasClass("comments")) 
    //call secondary dialog open event
  else
    //call default dialog open event
});

我认为有一个错误。

tr没有最接近的td,因为td是tr的子代。最接近tr的元素是正则tbody或table。

要访问td,您必须使用:

$("#timeline_table").on("click", "tbody tr", function(e){
 if ($(e.target).children("td:eq(indexNo)").hasClass("comments")) 
  //call secondary dialog open event
 else
  //call default dialog open event

});