javascript 带有 $index 绑定的交替行样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11231256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:28:35  来源:igfitidea点击:

alternate row style with $index binding

javascriptknockout.jsknockout-2.0

提问by Leland Richardson

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 $indexcontext variable.

我在使用 foreach 绑定上下文将交替行 css 类应用于淘汰模板时遇到问题。我正在将淘汰赛 2.1 与可用的$index上下文变量一起使用。

This is whats confusing:

这是令人困惑的:

My Template

我的模板

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

results in no altclasses being applied, however:

导致没有alt应用类,但是:

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

works properly and displays the row number.

工作正常并显示行号。

回答by Leland Richardson

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

我为此苦苦挣扎了几分钟,发现自从在淘汰赛 2.1 中引入了新的绑定上下文变量(如$index)以来,这个问题并没有真正被涵盖

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

我犯的错误是我只是忘记了它$index本身是一个可观察的,如果我们在 data-bind 属性的表达式中使用它,则必须解包。IE,

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

should become

应该成为

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

woops :)

呜呜:)

回答by Maarten

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

不要用 Javascript 做交替行样式,使用更有效的 CSS :)

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

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