How To Detect Which Is Clicked
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(docum
Solution 1:
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 --><scriptsrc="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><tableclass="table"><tr><tdclass="td1"></td><tdclass="td2">A</td><tdclass="td3">B</td><tdclass="td4">C</td><tdclass="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>
Solution 2:
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);
});
Post a Comment for "How To Detect Which Is Clicked"