Aurelia.js 单击后插入 CSS class 并仅绑定单击的行

Aurelia.js inserting CSS class after click and bind just the row clicked

我的代码可以正常工作,但是我有一个错误,因为 repeat.for 所有的 td 都改变了颜色,实际上我只想改变 1 行改变颜色,我点击的那一行。

有人知道如何在 aurelia 中解决这个问题。

谢谢

js:

isSelected = false;
new = 'will change the color'; 
changeColor() {
 alert(this.new);
 this.isSelected = !this.isSelected;
}

css:

.is-row-selected {
 background: green !important;
}

.is-row-not-selected {
  background:#f9f9f9 !important;
}

html:

<script src="https://jdanyow.github.io/rjs-bundle/node_modules/requirejs/require.js"></script>
    <script src="https://jdanyow.github.io/rjs-bundle/config.js"></script>
    <script src="https://jdanyow.github.io/rjs-bundle/bundles/aurelia.js"></script>
    <script src="https://jdanyow.github.io/rjs-bundle/bundles/babel.js"></script>
<table>
  <tr repeat.for="juice of $items" class="${isSelected ? 'is-row-selected' : 'is-row-not-selected'}" click.trigger="changeColor()">
   <td>${day | dateFormat: 'M/D/YYYY'}</td>
   <td>${time}</td>
   <td>${location}</td>
  </tr>
</table>

如果 isSelected$items 中每个项目的 属性,并且 changeColor()$items 中每个项目的函数,那么您需要要像这样调用函数 juice.changeColor(),您需要在 class 属性中使用 juice.isSelected。此外,您需要在 table 中列出的所有属性之前使用 juice.,例如${juice.location}.

您需要将视图更改为如下所示:

<table>
  <tr repeat.for="juice of $items" class="${juice.isSelected ? 'is-row-selected' : 'is-row-not-selected'}" click.trigger="juice.changeColor()">
   <td>${juice.day | dateFormat: 'M/D/YYYY'}</td>
   <td>${juice.time}</td>
   <td>${juice.location}</td>
  </tr>
</table>

但是,如果 changeColor() 是您的主 VM 上的一个函数,而不是 $items 中的每个项目,那么您需要将项目本身传递给该函数,以便它知道要更改 isSelected 属性 上的内容。

虚拟机:

changeColor(item) {
 alert(item.new);
 item.isSelected = !item.isSelected;
}

你的模板:

<table>
  <tr repeat.for="juice of $items" class="${juice.isSelected ? 'is-row-selected' : 'is-row-not-selected'}" click.trigger="changeColor(juice)">
   <td>${juice.day | dateFormat: 'M/D/YYYY'}</td>
   <td>${juice.time}</td>
   <td>${juice.location}</td>
  </tr>
</table>

鉴于你提供的代码,我真的不能说这些答案中的哪一个适合你,但它应该是其中之一。