简体   繁体   English

单击后突出显示表格行?

[英]Highlight Table row after clicking?

How can I highlight the table selected row? 如何突出显示表格的选定行? I am generating table row with JavaScript ES6 map function, with IDs and Names in the cells. 我正在使用JavaScript ES6映射函数生成表行,并在单元格中具有ID和名称。 So I need two thing. 所以我需要两件事。

  1. I want to change the color of the row which I have click and 我想更改单击的行的颜色,然后
  2. I need to get the ID of that particular row in a function? 我需要获取函数中特定行的ID吗?

My code looks something like this 我的代码看起来像这样

<table border="0" cellspacing="0" cellpadding="0">
    ${users? users.map((user) => html`
    <tr>
        <td style="width: 104px;">user.id</td>
        <td style="width: 175px;">
            user.name
        </td>

    </tr>
    `) : ''}
</table>

I need to get the ID of that particular row in a function? 我需要获取函数中特定行的ID吗?

You can bind on-click handler on tr with anonymous function to pass user to your function. 您可以将tr on-click处理程序与匿名函数绑定on-click以将user传递给您的函数。

<tr on-click='${() => this.selectUser(user)}'>

In this way in selectUser function will receive user as parameter. 这样,在selectUser函数中将接收user作为参数。

I want to change the color of the row which I have click 我想更改我单击的行的颜色

You can manually manipulate the DOM by using some functions such as querySelector and setAttribute but I would recommend you to keep that state as a property. 您可以通过使用一些函数(例如querySelectorsetAttribute来手动操作DOM,但我建议您将该状态保留为属性。

In selectUser function selectUser函数中

selectUser (user) {
  this.selectedUser = user
}

then bind selected attribute on tr 然后在tr上绑定selected属性

<tr selected?='${user === selectedUser}' on-click='${() => this.selectUser(user)}'>

Live demo on stackblitz Stackblitz上的现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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