简体   繁体   中英

how to access table row object from an anchor within a cell?

i have a table with a few rows. i want to access the cells with the value that are in the same row as the anchor that triggers the function populateRow(); (i hope i explained it in a clear way). any idea how to do that?

<tr>
   <td>
         some value
   </td>
   <td>
       <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left" onclick="populateRow();">update</a>
   </td>
</tr>
<tr>
    <td>
          another value
    </td>
    <td>
        <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left" onclick="populateRow();">update</a>
   </td>
</tr>

The populateRow() function would need to know which anchor was clicked, so you'd need to either pass this to it to give it a reference to said anchor:

onclick="populateRow(this);"

function populateRow(anchor) {
  var row = $(anchor).closest("tr");
  var firstCellValue = row.find("td").first().text();
}

...and from there use .closest() to navigate up the DOM to the containing tr element.

Or, better, bind the click event handler with jQuery rather than putting it inline on every row:

 $(document).ready(function() { $("#idOfYourTable").on("click", "a", function(e) { var row = $(this).closest("tr"); var firstCellValue = row.find("td").first().text(); console.log(firstCellValue); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="idOfYourTable"> <tr> <td>Value 1</td> <td> <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left">update</a> </td> </tr> <tr> <td>Value 2</td> <td> <a href="#myPopup" data-rel="popup" class="ui-btn ui-btn-inline ui-corner-all ui-icon-check ui-btn-icon-left">update</a> </td> </tr> </table> 

(Click the "Run..." button to see it working.)

I don't know what is that populateRow() function for, but if you want to get value on the first td of the same tr , then you can try testing this:

onclick="alert($(this).closest('tr').find('td:first').text())"

if you want to pass it in populateRow() function, you can:

onclick="populateRow($(this).closest('tr').find('td:first').text())"

Or ... It would be more neat if you pass the element then process it later inside your function:

onclick="populateRow(this)"

function populateRow(elm) {
    var val = $(elm).closest('tr').find('td:first').text();
    alert(val);
}

Hope this helps. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM