【发布时间】:2017-07-10 13:57:28
【问题描述】:
我试图在单击按钮时更改表格中行的背景。目前,我的代码只会更改表中第一行的背景颜色,并且只会更改第一行。即使我单击另一行的按钮,它仍然会使第一行背景变为绿色。
如何让它通过相应的按钮更改每一行的背景? (即按钮在行中,当它被点击时,特定行的背景颜色会发生变化)
这是我的表格的 html 代码:
<template name="adminPage">
...
<tbody>
{{#each student}}
<tr class="accordion-toggle mainRow">
<td>{{> expandButton}}</td>
<td>{{Name}}</td>
<td>{{PhoneNumber}}</td>
<td>{{VipID}}</td>
<td>{{> buttonSelections}}</td>
</tr>
<tr>
<td colspan="12" class="hiddenRow">
...
</template>
<template name="buttonSelections">
...
<button class="btn btn-success btn-sm">
<span class="glyphicon glyphicon-log-in"> Check-In</span>
</button>
...
</template>
这是我的js代码:
Template.buttonSelections.events({
'click .btn-success, click .glyphicon-log-in'() {
$(this).closest('.mainRow').css({"background-color":"#13D620","color":"white"});
}
}
})
所以,问题在于选择特定的行。当我尝试时:
Template.buttonSelections.events({
'click .btn-success, click .glyphicon-log-in'() {
$('.mainRow').css({"background-color":"#13D620","color":"white"});
}
}
})
当我单击任何签入按钮时,我得到以下信息
【问题讨论】:
-
使用类而不是 id。
$('.mainRow').css('background-color', '#13D620'); $('.mainRow').css('color', 'white'); -
ids 对您的页面应该是唯一的。因此,您应该避免在循环中使用它们,除非您像使用id="{{this._id}}"那样从循环中的唯一值“构造”它们。在单击事件中,您可以访问事件处理函数中的this属性以“遍历”到closest行并应用您的更改。 PS 你可以为.css函数提供一个对象(例如.css({"background-color":"#13D620","color":"white"}) -
@haxxxton 我仍然对这将如何在我的代码上下文中工作感到有些困惑。到目前为止,我尝试过的一切都不起作用。我需要如何引用 this 属性才能获取该行?我试过像
this.$('.mainRow).css(...); -
您将使用
$(this).css(..)而不是$('.mainRow').. 根据您的上下文,您可能需要向上“遍历”以选择行(例如$(this).closest('.mainRow').css(...))。 -
@haxxxton 这两种方法似乎都不起作用。还有其他想法吗?
标签: javascript html css meteor