Given a jQuery Datatable, how can I determine if a click occurs on a certain column?
I have a jQuery DataTable instance populated with assorted data that is a summary of a database record. Currently, a click on a row opens a dialog box with all the fields of the corresponding database record. What I want to do is open a second dialog box if the column clicked has a specified class 'comments'
Currently, I initialize the datatable via
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
]
});
and have a click event bound to the dynamically populated rows:
$("#timeline_table").on("click", "tbody tr", timelineTableClickHandler);
This works fine for the default action of opening up the detail dialog, but I want to modify the function handler to
$("#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
});
However, $(this).closest("td").hasClass("comments")
is returning undefined, and when I put a breakpoint on that in Firebug, the following commands and output result
$(this).attr("id") prints out row id
$(this).closest("td") prints out jQuery( )
$(this).closest("td").text() prints out "", should be 0
The problem is here this
is pointing to the tr
, as you well know td
is a child of tr
so you cannot use .closest() on this
to find the clicked td
Instead you can use the target
property of the event
to find the actual source of the event and find the closest
td of that element
$("#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
});
There's a mistake I think.
tr has no closest td because td is a children of tr. The closest element to tr is regularry tbody or table.
To access the td's you have to use:
$("#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
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.