gpt4 book ai didi

javascript - 如何在 knockout.js css-binding 中添加 "clicked"条件?

转载 作者:太空宇宙 更新时间:2023-11-04 08:39:20 25 4
gpt4 key购买 nike

knockout.js中css-binding的文档提供了一个例子如下:

<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div>

<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially we don't apply the "profitWarning" class
};
viewModel.currentProfit(-50); // Causes the "profitWarning" class to be applied
</script>

这个例子似乎应用了“profitWarning”currentProfit 是负的。我想稍微改变一下,并在单击 div 时应用此类。我怎样才能将“点击”条件应用到这个例子中?另外,我想制作多个 div,一次只应用一个样式(单击一个 div 时应用样式,单击另一个 div 时将其删除)

谢谢

最佳答案

您可以使用点击绑定(bind)。

The click binding adds an event handler so that your chosen JavaScript function will be invoked when the associated DOM element is clicked. This is most commonly used with elements like button, input, and a, but actually works with any visible DOM elemen

http://knockoutjs.com/documentation/click-binding.html

这是一个例子:

function viewModel() {
var self = this;
self.isSelected = ko.observable(false);
self.className = ko.pureComputed(function(){
return self.isSelected()? "SelectedClass" : "NotSelectedClass";
}, self);
self.change = function() {
self.isSelected(!self.isSelected());
}
}

ko.applyBindings(new viewModel());
<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 data-bind="text: className"></div> <br/>
<div data-bind="css: className">Inspect this Div</div> <br/>
<input type="button" data-bind="click: change" value="Toggle" />

对于你的第二个问题,你可以为每个 div 提供几个 bool 值来检查哪个被点击,将用户点击的设置为 true,然后将其余的设置为 false。

关于javascript - 如何在 knockout.js css-binding 中添加 "clicked"条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44249162/

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