Reputation: 307
I have the following case: I have a with some and . I need to detect which was clicked (eventually get the Id). I have build the following JS Fiddle as a reference.
jQuery(document).ready(function() {
$(".table").find("tr").click( function(){
alert("<tr> clicked");
var td2 = $(this).find(".td2:first").text();
alert(td2);
});
});
I have a .click() event and I am doing some actions when is clicked but I need to detect if a specific <td>
is clicked in order to exclude that TD.
Basically when any is clicked some actions should be done (unless a specific <td>
is clicked, and in that case nothing should be done)
What do you think?
Upvotes: 4
Views: 3348
Reputation: 9583
If you are trying to apply a specific action to td
tags except for when they contain a specific class, you can exclude the class with :not
. You can also apply your click event directly to the td
: JS Fiddle
$('td:not(.td2)').click(function () {
var clickedCell = $(this).text();
alert(clickedCell);
});
Upvotes: 4
Reputation: 388316
If you want to exclude the clicks in td2, then in the click handler you can use event.target
to get the actual element that is clicked.
jQuery(document).ready(function() {
$(".table tr").click(function(e) {
if ($(e.target).closest('td').is(':nth-child(2)')) {
snippet.log('td2 clicked');
return;
}
snippet.log("<tr> clicked");
var td2 = $(this).find("td:nth-child(2)").text();
snippet.log('td2: ' + td2)
});
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="table">
<tr>
<td class="td1"></td>
<td class="td2">A</td>
<td class="td3">B</td>
<td class="td4">C</td>
<td class="td5">D</td>
</tr>
<tr>
<td>1</td>
<td>A1</td>
<td>B1</td>
<td>C1</td>
<td>D1</td>
</tr>
<tr>
<td>2</td>
<td>A2</td>
<td>B2</td>
<td>C2</td>
<td>D2</td>
</tr>
<tr>
<td>3</td>
<td>A3</td>
<td>B3</td>
<td>C3</td>
<td>D3</td>
</tr>
</table>
Upvotes: 4