I want to set a list item's CSS to active when clicked. I have a working implementation, but I also need to remove the active class from any other li
elements within the ul
element.
<div class="row">
<ul data-bind="foreach: cats" class="list-group">
<li class="list-group-item" data-bind="click: catSelected, css: { active: isCatChosen() == true}">
<span data-bind="text: catName"></span>
<span class="badge" data-bind="text: catClicks"></span>
</li>
</ul>
</div>
<script>
var CatsViewModel = function() {
var catList = this;
catList.cat = ko.observable();
catList.cats = ko.observableArray([
{ 'catName' : 'Twins',
'catClicks' : ko.observable(0),
'catImage' : 'img/funnyCat.jpg',
'isCatChosen': ko.observable(false),
'catSelected': function() {
this.isCatChosen(true);
}
}, {
'catName' : 'Leopard',
'catClicks' : ko.observable(0),
'catImage' : 'img/leopard.jpg',
'isCatChosen': ko.observable(false),
'catSelected': function() {
this.isCatChosen(true);
}
},{
'catName' : 'Blue Eyes',
'catClicks' : ko.observable(0),
'catImage' : 'img/blueEyes.jpg',
'isCatChosen': ko.observable(false),
'catSelected': function() {
this.isCatChosen(true);
}
},{
'catName' : 'Mountain Lion',
'catClicks' : ko.observable(0),
'catImage' : 'img/mountainLion.jpg',
'isCatChosen': ko.observable(false),
'catSelected': function() {
this.isCatChosen(true);
}
},{
'catName' : 'Painted Lion',
'catClicks' : ko.observable(0),
'catImage' : 'img/paintedlion.jpg',
'isCatChosen': ko.observable(false),
'catSelected': function() {
this.isCatChosen(true);
}
}
]);
};
ko.applyBindings(new CatsViewModel());
</script>
答案 0 :(得分:1)
由于您将active
项目排除在外,因此您应该在CatsViewModel
中跟踪该项目。每只猫都不需要知道它是否有效。
<div class="row">
<ul data-bind="foreach: cats" class="list-group">
<li class="list-group-item" data-bind="click: $parent.catSelected,
css: { active: $parent.isCatChosen($data) }">
<span data-bind="text: catName"></span>
<span class="badge" data-bind="text: catClicks"></span>
</li>
</ul>
</div>
var CatsViewModel = function(cats) {
var catList = this;
catList.activeCat = ko.observable();
catList.cats = ko.observableArray(cats);
catList.isCatChosen = function (cat) {
return catList.activeCat() === cat;
};
catList.catSelected = function (cat) {
catList.activeCat(cat);
};
};
然后,您可以删除添加到每只猫的所有不必要的方法和其他属性。
var cats = [
{
'catName' : 'Twins',
'catClicks' : ko.observable(0),
'catImage' : 'img/funnyCat.jpg',
}, {
'catName' : 'Leopard',
'catClicks' : ko.observable(0),
'catImage' : 'img/leopard.jpg',
},{
'catName' : 'Blue Eyes',
'catClicks' : ko.observable(0),
'catImage' : 'img/blueEyes.jpg',
},{
'catName' : 'Mountain Lion',
'catClicks' : ko.observable(0),
'catImage' : 'img/mountainLion.jpg',
},{
'catName' : 'Painted Lion',
'catClicks' : ko.observable(0),
'catImage' : 'img/paintedlion.jpg',
}
];
ko.applyBindings(new CatsViewModel(cats));
答案 1 :(得分:0)
$('.list-group li').click(function(){
$('list-group li').each(function(){
$(this).removeClass('active');
});
$(this).addClass('active');
});