基本上,我有可观察的滑块数组,每个滑块都应该有自己的可观察片段数组,其中包含一些用于 HTML 中 CSS 绑定的属性.我的第一个问题是我不确定应该使用哪个 foreach 绑定:由于某种原因,这个不起作用:<p data-bind="text: day"></p>这个有效,但我不确定我应该在哪些情况下使用这个:<p data-bind="text: day"></p><!--/ko -->我的第二个问题是我不知道如何从段 observable 数组中应用想要的 CSS 样式.我已经试过了:<div class='slider-segment' data-bind="style: {left: segment_left, width:segment_width,backgroundColor:segment_color}"></div>但这行不通.我想我需要将这些属性也作为可观察对象,但我不确定如何在 ViewModel 中正确执行此操作我想知道我应该使用什么 foreach 绑定.我什么时候可以使用注释"foreach bindng,什么时候可以使用普通的,我想知道如何重新编写我的代码,以便我可以从段可观察数组中绑定 CSS 属性.谢谢! 解决方案我变了self.segments = ko.observableArray([segments]);与self.segments = ko.observableArray(segments);见:http://jsfiddle.net/x4a8pkmu/我想知道我应该使用什么 foreach 绑定.我什么时候可以使用评论" foreach 绑定,我什么时候使用正常的绑定,我会想知道如何重新编写我的代码,以便我可以从分割可观察数组如果您不想要容器元素,注释"语法很有用.例如:<!-- ko foreach: myList --><li data-bind="text: myProp"></li><!--/ko -->产生与以下相同的效果:<li data-bind="text: myProp"></li>I have prepared a small jsfiddle here: http://jsfiddle.net/zb8jwre6/Basically, I have observable array of sliders, and each slider should have it's own observable array of segments, which contain some properties for CSS-binding in HTML.My first problem is that I'am not sure which foreach bind should i use:This one doesn't work for some reason:<div data-bind "foreach: $root.sliders"> <p data-bind="text: day"></p></div>This one works, but I am not sure in which cases should I use this one:<!-- ko foreach: sliders--> <p data-bind="text: day"></p><!-- /ko -->My second problem is that I don't know how to apply wanted CSS stylings from segment observable array.I have tried this:<div class='slider-segment' data-bind= "style: {left: segment_left, width:segment_width, backgroundColor: segment_color}"></div>But this does not work. I think I need to make those properties also as observables, but I am not sure how to do this properly in ViewModelI would like to know what foreach binding should I use. When can I use "comment" foreach bindng and when do I use normal one, and I would like to know how to rework my code, so I can bind CSS properties from segments observable array.Thank you! 解决方案 I've changedself.segments = ko.observableArray([segments]);withself.segments = ko.observableArray(segments);See:http://jsfiddle.net/x4a8pkmu/ I would like to know what foreach binding should I use. When can I use "comment" foreach bindng and when do I use normal one, and I would like to know how to rework my code, so I can bind CSS properties from segments observable arrayThe "comment" syntax is useful if you do not want a container element. For example:<ul><!-- ko foreach: myList --> <li data-bind="text: myProp"></li><!-- /ko --></ul>produces the same effects as:<ul data-bind="foreach: myList"> <li data-bind="text: myProp"></li></ul> 这篇关于如何正确编码 foreach 和样式绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-23 03:21
查看更多