简体   繁体   中英

Pure JavaScript select table row as object when click

I have a table as following I need when click on a row cell select this row and convert as a JavaScript object using pure JavaScript.

<table id="auditors">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td> 
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td> 
    <td>94</td>
  </tr>
</table>

You can do using addEventListener :

 var trs = document.querySelectorAll("tr"); for (var i = 0; i < trs.length; i++) (function (e) { trs[e].addEventListener("click", function () { console.log(this); }, false); })(i); 
 <table id="auditors"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> 

Here, the this will be a HTMLElement Object. The logged item will be the <tr> itself.

<tr>
  <td>Jill</td>
  <td>Smith</td> 
  <td>50</td>
</tr>

If you want it to make it like an Object that contains your format, then you need to do:

 var trs = document.querySelectorAll("tr"); for (var i = 0; i < trs.length; i++) (function (e) { trs[e].addEventListener("click", function () { console.log({ "FirstName": this.querySelectorAll("*")[0].innerHTML.trim(), "LastName": this.querySelectorAll("*")[1].innerHTML.trim(), "Age": this.querySelectorAll("*")[2].innerHTML.trim() }); }, false); })(i); 
 <table id="auditors"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> 

When you click the row, you will get the object as:

{
  "FirstName": "Jill",
  "LastName": "Smith",
  "Age": "50"
}

Here I have assumed the <th> as the Object Keys.

The interesting part here is to make it generic by not hardcoding the keys/columns. This can be done by using the th element texts as keys when building the object:

 [].slice.call(document.querySelectorAll("#auditors tr"), 1).forEach(function(row){ row.addEventListener("click", function(){ var ths = document.querySelectorAll("#auditors th"); var obj = [].reduce.call(ths, function(obj, th, i){ obj[th.textContent] = row.cells[i].textContent; return obj; }, {}); console.log(obj); }); }); 
 <table id="auditors"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> </tr> <tr> <td>Jill</td> <td>Smith</td> <td>50</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table> 

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