KnockoutJS 数据
function ExampleViewModel() {
var self = this;
self.ExampleData = ko.observableArray([]);
self.update = function() {
$.ajax("test.json", {
success: function(allData) {
var mappeddata = $.map(allData, function(item) {
return new DataItem(item)
});
self.ExampleData(mappeddata);
}
});
}
}
function DataItem(data) {
this.Name = ko.observable(data.name);
}
var exampleViewModel = new ExampleViewModel();
ko.applyBindings(exampleViewModel);
HTML 数据
<div data-bind="foreach: ExampleData">
<div class="has-topic-background-color">
</div>
</div>
我如何在每个 foreach 循环中更改下面 div 的类 div class="has-topic-background-color
i need if in first loop its show red color then in second loop i need blue color insted of red
最佳答案
你可以使用css绑定(bind)
http://knockoutjs.com/documentation/css-binding.html
function ViewModel() {
var self = this;
self.data = ko.observableArray([1, 2, 3, 4, 5, 6, 7, 8, 9]);
self.className = function(index) {
return index % 2 === 0? 'redClass' : 'blueClass';
};
self.textValue = function(index) {
return 'Data for index ' + index + ' has background ' + self.className(index);
}
}
$(document).ready(function () {
var myViewModel = new ViewModel();
ko.applyBindings(myViewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div>
You can inspect the element to see the class name
</div>
<br/>
<div data-bind="foreach: data">
<div data-bind="text: $parent.textValue($index()), css: $parent.className($index())"></div>
</div>
关于javascript - 如何在knockout js中为每个foreach循环添加不同的css类到html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43133597/