alternate row style with $index binding

倾然丶 夕夏残阳落幕 提交于 2019-12-04 09:53:34

问题


I am having trouble getting an alternate-row css class applied to a knockout template with a foreach binding context. I am using knockout 2.1 with the available $index context variable.

This is whats confusing:

My Template

<li class="row" data-bind="css: { alt: $index%2 }"></li>

results in no alt classes being applied, however:

<li class="row" data-bind="text: $index"></li>

works properly and displays the row number.


回答1:


I struggled with this for a couple minutes and found that this question hadn't really been covered since the new binding context variables (like $index)had been introduced in knockout 2.1

The mistake I was making was that I simply forgot that $index itself is an observable, and must be unwrapped if we are using it in an expression in the data-bind attribute. ie,

<li class="row" data-bind="css: { alt: $index%2 }"></li>

should become

<li class="row" data-bind="css: { alt: $index()%2 }"></li>

woops :)




回答2:


Don't do alternate row styling with Javascript, use CSS which is way more efficient :)

https://developer.mozilla.org/en-US/docs/CSS/:nth-child



来源:https://stackoverflow.com/questions/11231256/alternate-row-style-with-index-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!