简体   繁体   English

KnockoutJS data-bind =“Visible:”有两个条件不起作用

[英]KnockoutJS data-bind=“Visible :” with two conditions is not working

A simple thing I am trying to workout with KnockoutJS. 我想用KnockoutJS锻炼一件简单的事情。

I have two dropdowns and a textbox . 我有两个dropdowns和一个textbox

What I need 我需要的

If both the dropdowns are selected, then only I should get the checkbox displayed. 如果同时选择了两个下拉菜单,那么只有我应该显示复选框。 Otherwise, the text input should not visible. 否则,文本输入应该不可见。

What I tried: 我尝试了什么:

Here is my fiddle: https://jsfiddle.net/vikash208/z4x5meua/13/ 这是我的小提琴: https//jsfiddle.net/vikash208/z4x5meua/13/

I used something like this: 我使用过这样的东西:

data-bind="visible: selectedValue && selectedControl"

From the above, the conditions are verified as below: 从上面可以看出,条件如下:

IF selectedValue IS TRUE AND selectedControl IS NOT UNDEFINED

Kindly provide me a solution and also where I went wrong with it. 请给我一个解决方案,并在我错误的地方。 I am a beginner of knockoutJS 我是knockoutJS的初学者

When you use multiple conditions in a binding, you need to unwrap the observables so the entire expression can be evaluated. 在绑定中使用多个条件时,需要打开observable以便可以计算整个表达式。

To do this, just add brackets after the observable: 为此,只需在observable后添加括号:

<input type="text" class="form-control" data-bind="visible: selectedValue() && selectedControl()" />

JSFiddle 的jsfiddle

You could also create another computed observable with your condition in it (note, you still unwrap the observables in the computed observable). 您还可以使用其中的条件创建另一个计算的observable(注意,您仍然在计算的observable中打开observable)。 This is probably the better option since it keeps the logic in your view model and can be reused. 这可能是更好的选择,因为它将逻辑保留在视图模型中并且可以重用。

Txt.showCondition = ko.computed(function() {
    return this.selectedItem() && this.selectedValue()
}, this);

Then just bind the input to this instead: 然后只需将输入绑定到此:

<input type="text" class="form-control" data-bind="visible: showCondition" />

JSFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM