简体   繁体   中英

How to make first column's every row clickable to get data from that whole row? JavaScript

I'm trying to make a table's first column's each row (in this case order IDs) clickable so that I can display more info from this specific order ID in another container on my website. I looped through some JSON data to create the table like this:

function printData(jsonData) {
    let myTable = document.getElementById("jsonTable")
    for(let i=0; i < jsonData.length; i++) {
        let row = `<tr>
                        <td>${jsonData[i].orderid}</td>
                        <td>${jsonData[i].customerid}</td>
                        <td>${jsonData[i].customer}</td>
                        <td>${jsonData[i].invaddr}</td>
                        <td>${jsonData[i].delivaddr}</td>
                        <td>${jsonData[i].deliverydate}</td>
                        <td>${jsonData[i].respsalesperson}</td></tr>`


            jsonTable.innerHTML += row
    }
}

And this is how my HTML file looks like:

        <div class="datatable">

            <div class="datatablecontent">
                <table class="jsontable">
                    <tr id="jsontr">
                        <th>Order ID</th>
                        <th>Customer ID</th>
                        <th>Customer</th>
                        <th>InvAddr</th>
                        <th>Delivery Address</th>
                        <th>Delivery Date</th>
                        <th>Resp. For Sale </th>
    
                        <tbody id="jsonTable">
    
                        </tbody>
                    </tr>
    
                </table>
            </div>
        </div>

While iterating over jsonData , you can declare a callback in an event listener.

Because you're using template literals, I'm keeping it concise and passing the row index. You can also pass the data itself by adding an event listener in JS, to do that you'll need to access the element.

 function logRowData(index) { console.log(jsonData[index]) } let jsonData = [ {orderid: 0, customerid:14, customer: 'abc'}, {orderid: 1, customerid:25, customer: 'xyz'} ] printData(jsonData) function printData(jsonData) { let myTable = document.getElementById("jsonTable") for(let i=0; i < jsonData.length; i++) { let row = `<tr> <td onclick={logRowData(${i})}>${jsonData[i].orderid}</td> <td>${jsonData[i].customerid}</td> <td>${jsonData[i].customer}</td></tr>` jsonTable.innerHTML += row } }
 <div class="datatable"> <div class="datatablecontent"> <table class="jsontable"> <tr id="jsontr"> <th>Order ID</th> <th>Customer ID</th> <th>Customer</th> <tbody id="jsonTable"> </tbody> </tr> </table> </div> </div>

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