How to detect which <td> is clicked

孤街醉人 提交于 2020-01-03 13:32:25

问题


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?


回答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 -->
<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>



回答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);
});


来源:https://stackoverflow.com/questions/32470251/how-to-detect-which-td-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!