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
alternate row style with $index binding
提问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 $index
context 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 alt
classes 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 $index
itself 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 :)