gpt4 book ai didi

javascript - 具有两个功能的切换

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

我正在尝试设置一个复选框,当给定 true 值时将加载信息,当给定 false 值时卸载该信息。目前我有两个具有这些功能的按钮,但希望有一个快速访问切换。然而,我似乎无法弄清楚如何为切换功能设置 if true/false。

HTML - 用于加载的硬编码按钮。

<span class="label" data-bind="css: {click: function () {$root.loadLayerSource(Source, ReadableName, Type, URL, Description)}">Load</span>

JS:

//Disable layers if checkbox is false
this.disableLayer = function (layerId, type) {
//
}

// .....

//Enable layers if checkbox is true
this.loadLayerSource = function (source, name, type, url, description){
//...
}

最佳答案

您在评论中说过:

I don't want to show or hide HTML elements, rather I need to execute two different functions loadLayerSource or disableLayer

如果没有显示/隐藏并且纯粹是调用函数的问题,则通过 checked 绑定(bind)将复选框绑定(bind)到 bool 可观察对象并订阅它:

var vm = {
showing: ko.observable(false),
output: ko.observableArray()
};
vm.showing.subscribe(function(newValue) {
if (newValue) {
doThis();
} else {
doThat();
}
});
ko.applyBindings(vm, document.body);

function doThis() {
vm.output.push("Doing 'this' because value was true");
}

function doThat() {
vm.output.push("Doing 'that' because value was false");
}
<label>
<input type="checkbox" data-bind="checked: showing">
Show
</label>
<div data-bind="foreach: output">
<div data-bind="text: $data"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<小时/>

当我认为您主要显示/隐藏内容时的原始答案,以及可选订阅:

通过 checked 绑定(bind)将复选框绑定(bind)到 bool 可观察量,然后根据该可观察量的值显示/隐藏其他信息。

var vm = {
showing: ko.observable(false)
};
ko.applyBindings(vm, document.body);
<label>
<input type="checkbox" data-bind="checked: showing">
Show
</label>
<div data-bind="visible: showing">This is visible when showing</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

如果您需要在可观察值发生变化时启动一些进一步的流程,您可以通过订阅来实现。

var vm = {
showing: ko.observable(false),
loading: ko.observable(false),
data: ko.observable(null),
loadData: function() {
this.loading(true);
setTimeout(function() {
vm.loading(false);
vm.data("The data is ready now");
}, 500);
}
};
vm.showing.subscribe(function(newValue) {
if (newValue && !vm.data()) {
vm.loadData();
}
});
ko.applyBindings(vm, document.body);
<label>
<input type="checkbox" data-bind="checked: showing">
Show
</label>
<div data-bind="visible: showing">
<div data-bind="visible: loading">Loading...</div>
<div data-bind="visible: data, text: data"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

关于javascript - 具有两个功能的切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32266149/

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