#HTML <tr class="odd"> <td>...</td> <td>...</td> <td>...</td> </tr> <tr class="even"> <td>...</td> <td>...</td> <td>...</td> </tr> 

When clicking on a cell in the table, it is necessary to go up the DOM model and find the first element encountered and get all the information from it, i.e. contents of child fields. Tried to do the following, but returns an Object object, or undefined, if I specify an index

 (this).onclick = function(){ var a = $(this).parent().find("tr").val() alert(a)} 

How can you implement an idea?

  • one
    найти первый встреченный элемент и получить из него всю информацию - take the contents of the current line? or the next td ? And who is (this).onclick ? - Alexey Shimansky
  • It is necessary to get the contents of all <td>, i.e. the contents of the current line. (this) .onclick - click event, from the point of view of syntax there are no problems - Zireael
  • The problem in terms of common sense. (this).onclick specifies the only click handler for this item. If other handlers were hung on these elements, they will not be called. - tutankhamun
  • In this context, $(this).click(...) or $(this).on('click', ...) is better - tutankhamun

2 answers 2

For example, you can:

 $('td').on('click', function(e){ var parent = $(e.currentTarget).parent(); if(parent){ //ищите, что вам нужно var results = parent.find('td'); console.log('значение 1-й ячейки: ' + $(results[0]).html()); console.log('значение последней ячейки: ' + $(results[results.length - 1]).html()); } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr class="odd"> <td>1</td> <td>2</td> <td>3</td> </tr> <tr class="even"> <td>4</td> <td>5</td> <td>6</td> </tr> </table> 

    Find the closest ancestor on the selector

     var row = $(this).closest("tr"); 

    Then select the selectors from $(__селектор__, row)...