I am trying to find out if the last td
of an tr
was clicked. This is my HTML example:
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td>Clicked</td>
</tr>
</table>
And this is my currently javascript code (not working like that):
$('table').on('click', 'tr', function(e) {
if ($(this).find('td').is(':last-child')){
alert("Last td clicked!");
}
});
Note : I need to use the tr-selector
for other purpose. So it it important, that the on click refers to the tr
.
Try like following using tr td:last-child
selector.
$('table').on('click', 'tr td:last-child', function (e) { alert("Last td clicked!"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Foo</td> <td>Bar</td> <td>Clicked</td> </tr> </table>
UPDATE: as per updated question
$('table').on('click', 'tr', function (e) { if($(e.target).is(':last-child')) { alert("Last td clicked!"); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Foo</td> <td>Bar</td> <td>Clicked</td> </tr> </table>
You don't need that .find()
. Also, do you want to check if the last td
or las tr
was clicked? Either way, you just have to do it like this:
$('table').on('click', 'td', function(e) {
if($(this).is(':last-child')){
alert("Last td clicked!");
}
});
Add the event listener directly to the last child
Html
<table>
<tr>
<td>Foo</td>
<td>Bar</td>
<td>Clicked</td>
</tr>
</table>
Javascript
$('table').on('click', 'tr td:last-child', function(e) {
alert("Last td clicked!");
});
This answer assumes that the event hander is common to all the <td>
elements and want to distinguish between the last element
Without changing the event handler:
The event object holds the reference of the element that was clicked. This can be used.
The target
property in the event
object contains the reference of the element that is actually clicked. jQuery is()
can be used to check if the element is the last in the <tr>
.
$('table').on('click', 'tr', function(e) {
console.log($(e.target).is($(this).find('td:last')));
// OR
// console.log($(e.target).is(':last-child'));
});
Binding event on <td>
The event can be bind on the <td>
elements inside the <table>
and :last-child
selector can be used with is()
to check if the element that is clicked is the last child.
$('table tr').on('click', 'td', function(e) {
console.log($(this).is(':last-child'));
});
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.