gpt4 book ai didi

javascript - knockout js - 单击 foreach 语句下的列表时如何更改列表颜色?

转载 作者:行者123 更新时间:2023-11-28 04:29:33 26 4
gpt4 key购买 nike

我正在使用最新版本的 knockout js之一,并且在单击时更改颜色时遇到一些问题。我想在用户单击其中一个列表时更改列表的颜色,并保留列表的颜色,直到用户单击另一个列表,但到目前为止还没有运气。

我的想法之一是从点击列表中获取索引值并添加具有反转颜色的CSS类(颜色:黑色,背景颜色:白色)。

html

<div class="left_pane">
<div class="location_list" data-bind="foreach: locations">
<div data-bind="text: title, click: $parent.is_selected, css: {selected: $parent.current_index == $index }"></div>
</div>
</div>

CSS

.left_pane {
background-color: black;
color: white;
padding-top: 10px;

height: 850px;
}

.location_list {
padding-top: 10px;
padding-bottom: 10px;
cursor: pointer;
cursor: hand;
}

.selected {
background-color: white;
color: black;
}

js

var locations = [

{'title': 'title01'},
{'title': 'title02'},
{'title': 'title03'},
{'title': 'title04'},
{'title': 'title05'}

];

function InitViewModel() {
// main viewModel
var self = this;

self.current_index = ko.observable('');

console.log(self.current_index());

self.is_selected = function(data, event) {
// save clicked row's index to current_index.
self.current_index($(event.target).index());
// self.current_index($(event.target).index());
console.log(self.current_index());
};
}

ko.applyBindings(new InitViewModel());

感谢您的支持和建议。

最佳答案

你已经很接近了!我发现在其自己的可观察对象中跟踪所选元素并将其设置为单击的元素更容易。您可以使用相同的方法将类更改为selected。如果您需要选择多个,我通常使用跟踪所选状态的对象。 (即 'title': 'title01', selected: false }),然后只需将点击函数更改为 location.selected(true)

从你的代码到我的代码最大的变化是不再费心去追踪 location 项,而只需要它是什么。如果它匹配完美,如果不匹配,您就有了您需要的。

function InitViewModel() {
// main viewModel
var self = this;

self.Selected = ko.observable("");

self.locations = [{
'title': 'title01'
}, {
'title': 'title02'
}, {
'title': 'title03'
}, {
'title': 'title04'
}, {
'title': 'title05'
}
];

self.current_index = ko.observable('');

console.log(self.current_index());

self.select = function(location) {
self.Selected(location);
};
}

ko.applyBindings(new InitViewModel());
.left_pane {
background-color: #BBB;
color: white;
padding-top: 10px;
height: 850px;
}

.location_list {
padding-top: 10px;
padding-bottom: 10px;
cursor: pointer;
cursor: hand;
}

.selected {
background-color: white;
color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div class="left_pane">
<div class="location_list" data-bind="foreach: locations">
<div data-bind="text: title, click: $parent.select, css: {selected: $data === $parent.Selected() }"></div>
</div>
</div>

关于javascript - knockout js - 单击 foreach 语句下的列表时如何更改列表颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44733357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com