我对敲出js非常陌生。我正在尝试一个功能,当用户单击按钮时,值会更改。有点像开/关按钮。我将后端的值存储为true和false。 任何帮助将不胜感激。
.js代码
return class MyClass {
constructor{
self.switch = ko.observable();
}
changeValue(tgt, evt) {
let self = this;
if (self.switch ==false) {
self.switch = on;
}
}
}
.html代码
<button data-bind="click: changeValue">
<span data-bind="text: switch() ? 'On' : 'Off'"></span>
</button>
答案 0 :(得分:2)
您返回模型而不在代码示例中应用绑定。
这是一种执行所需操作的简洁方法:
class Model {
constructor() {
this.switch = ko.observable(false);
}
changeValue() {
this.switch(!this.switch())
}
}
ko.applyBindings(new Model());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button data-bind="click: changeValue">
<span data-bind="text: $data.switch() ? 'On' : 'Off'"></span>
</button>
答案 1 :(得分:0)
class MyClass {
constructor(){
let self = this;
//this is how you set the initial value for an observable.
this.switch = ko.observable(false);
//functions have to publicly available for the html to be able to access it.
this.changeValue = function(tgt, evt) {
//an observable is a function, and you access the value by calling it with empty parameters
if (self.switch() === false) {
//an observable's value can be updated by calling it as a function with the new value as input
self.switch(true);
}
else {
self.switch(false);
}
}
}
}
//this needs to be called at the end of the js, for the bindings to be applied
ko.applyBindings(new MyClass());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<button data-bind="click: changeValue">
<span data-bind="text: $data.switch() ? 'On' : 'Off'"></span>
</button>