简体   繁体   中英

How to pass html table cell value to javascript variable?

I have no experience with javascripting and need a solution for my html page with a table generated automatically by a shell script. Script outputs the HTML code below.

cat plstable.html
<html><head></head><body><table>
<tr><td>1</td><td> The Fratellis - Chelsea Dagger </td></tr>
<tr><td>2</td><td> Connect Northants: Eternal / Bebe Winans - I Wanna Be The Only One</td></tr>
<tr><td>3</td><td> Virgin_UK_128</td></tr>
</table></body></html>

I need a javascript with onclick when the user clicks the first entry in the table row (eg 1, 2 or 3), javascript gets the value from the page named plstable.html, set a variable value (like var x = 1) and run a command in the shell like "mpc play + x" to play the first entry. Javascript should be a seperate file because the shellscript generating the html table becomes complex in the case of adding java code to shell script.

This code

  1. Adds a click (event) listener to every first <td> of every <tr>
  2. On click the text is parsed to int (base10), and the number is passed to the handler function ( getNumber(val) )
  3. The handler function prints the value read from the <td> to the console

 // "grabbing" each row const rows = document.getElementsByTagName('tr') // iterating over each row for (let i = 0, length = rows.length; i < length; i++) { // grabbing the first child element in each row (so no text // or other type of nodes - only elements) // then adding a click event listener with a callback function rows[i].firstElementChild.addEventListener('click', function(e) { // calling the "designed" function in the event listener // callback getNumber(parseInt(this.textContent, 10)) }) } // the handling function function getNumber(val) { console.log(val) }
 td:first-child { cursor: pointer; font-weight: 700; }
 <table> <tr> <td>1</td> <td> The Fratellis - Chelsea Dagger </td> </tr> <tr> <td>2</td> <td> Connect Northants: Eternal / Bebe Winans - I Wanna Be The Only One</td> </tr> <tr> <td>3</td> <td> Virgin_UK_128</td> </tr> </table>

ES6

 [...document.querySelectorAll("table tr td:first-child")] .forEach((td) => td.addEventListener("click",getNumber)) function getNumber() { console.log(+this.textContent) }
 td:first-child { cursor: pointer; font-weight: 700; }
 <table> <tr> <td>1</td> <td> The Fratellis - Chelsea Dagger </td> </tr> <tr> <td>2</td> <td> Connect Northants: Eternal / Bebe Winans - I Wanna Be The Only One</td> </tr> <tr> <td>3</td> <td> Virgin_UK_128</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