【问题标题】:Change css background color on click in meteor单击流星时更改css背景颜色
【发布时间】: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


【解决方案1】:

您可以通过挂钩event.target 来访问点击的元素。

Template.buttonSelections.events({
  'click .btn-success, click .glyphicon-log-in': function(e) {
   $(e.target).closest('.mainRow').css({"background-color":"#13D620","color":"white"});
   }
  }
});

【讨论】:

  • 是的。而已。非常感谢。我很感激。
  • :) 我们最终到达了那里
猜你喜欢
  • 2020-11-28
  • 2019-09-01
  • 2014-06-12
  • 1970-01-01
  • 2014-10-09
  • 2011-06-05
  • 2013-09-27
  • 2017-08-02
相关资源
最近更新 更多