javascript 敲除数据绑定 if else 条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19726214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:37:11  来源:igfitidea点击:

Knockout data-bind if else condition

javascriptdata-bindingknockout.js

提问by Mujahid

In my current project, I have a knockout binding where the layout height should be applied according to the value received as true or false. Following is my binding code

在我当前的项目中,我有一个淘汰赛绑定,其中应根据收到的值为 true 或 false 应用布局高度。以下是我的绑定代码

data-bind="style: {height: showOld ? '392px' : '275px'}"

The showOldgives either trueor falsecorrectly, but, regardless what it returns, it always take 392px. If the showOldgives truethen 392pxshould return else 275pxshould return. Any help to fix this issue is highly appreciate.

showOld给出任何truefalse正确的,但是,不管它返回什么,它总是需要392px。如果showOld给出true那么392px应该返回否则275px应该返回。非常感谢解决此问题的任何帮助。

Thanks

谢谢

回答by nemesv

If your showOldis ko.observablethen you need to write showOld()(because ko.observableis a function) to get its value in your expression:

如果您showOld是,ko.observable那么您需要编写showOld()(因为ko.observable是一个函数)以在您的表达式中获取其值:

data-bind="style: {height: showOld() ? '392px' : '275px'}"

From the documentation:

文档

To readthe observable's current value, just call the observable with no parameters.

To writea new value to the observable, call the observable and pass the new value as a parameter. For example, calling myViewModel.personName('Mary')will change the name value to 'Mary'.

读取observable 的当前值,只需调用不带参数的 observable。

要将新值写入observable,请调用 observable 并将新值作为参数传递。例如,调用myViewModel.personName('Mary')会将名称值更改为“Mary”。