Clicking a row except for the first td

2019-04-29 12:08发布

问题:

I am trying to click a table row and perform an action. However if they click the first <td> cell I do not want that to perform the action.

Here is the code I have so far:

jQuery('#dyntable tbody tr').live('click', function () {
        nTr = jQuery(this)[0];

        openMessage(oTable, nTr);
    });

This works as intended, except the first <td> has a check box, so if they click in that cell I do not want to call the openMessage(oTable, nTr); function.

I also still need nTr to = the contents of the row.

回答1:

Use target of click within row, and check the index of TD

Simplified DEMO: http://jsfiddle.net/WLR9E/

jQuery('#dyntable tbody tr').live('click', function (evt) {
    var $cell=$(evt.target).closest('td');
    if( $cell.index()>0){
       openMessage(oTable, this);
}
});

live() is deprecated , if using jQuery >= 1.7 convert to on(). Following assumes main table is a permanent asset in page.

jQuery('#dyntable').on('click','tbody tr', function (evt) {
    var $cell=$(evt.target).closest('td');
    if( $cell.index()>0){
       openMessage(oTable, this);
   }
});

This line in your code is redindant, it simply returns the same as this

nTr = jQuery(this)[0];


回答2:

 $("#dyntable tbody").on('click', 'tr td:not(:first-child)',function () {
    alert("success");
});

$(document).ready(function ()
{
   $("#tbluserdata tbody").on('click', 'tr td:not(:first-child)', function () {
      alert("write code");
    });
  
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
    </head>
  <body>
    <table border="2" width="50%" id="tbluserdata">
      <thead>
        <tr>
          <th>Id</th>
        <th>Name</th>
        <th>Address</th>
          <th>Action</th>
          </tr>
        </thead>
      <tbody>
      <tr>
        <td>1</td>
        <td>aaa</td>
        <td>ccc</td>
         <td>delete</td>
        </tr>
      <tr>
        <td>1</td>
        <td>aaa</td>
        <td>ccc</td>
        <td>delete</td>
        </tr>
      <tr>
        <td>1</td>
        <td>aaa</td>
        <td>ccc</td>
        <td>delete</td>
        </tr>
        </tbody>
      </table>
    </body>
</html>



回答3:

This'll do the trick:

jQuery('#dyntable tbody tr td:not(:first)').live('click', function () {
        nTr = jQuery(this).parent('tr')[0];

        openMessage("asdf", nTr);
});


function openMessage(oTable, nTr){
  console.log(nTr);
  alert('something happened');    
}

Here's the fiddle to test: DEMO



回答4:

You could try adding a class or unique id to that <td> element. Then in your handler you test against it.

jQuery('#dyntable tbody tr').live('click', function () {
  var $thisRow = jQuery(this); // cache this selector for performance
  nTr = $thisRow[0];
  if (!$thisRow.hasClass('not_this_one')){
    openMessage(oTable, nTr);
  }
});