KnockoutJS - 可见绑定
顾名思义,此绑定根据绑定中传递的值使关联的 DOM 元素可见或隐藏。
语法
visible: <binding-condition>
参数
当参数转换为类似 false 的值(例如布尔值 false、0、null 或 undefined)时,绑定会为 yourElement.style.display 设置 display:none,使其隐藏。这比 CSS 中任何现有的样式都具有更高的优先级。
当参数转换为类似 true 的值(例如布尔值 true、非空对象或数组)时,绑定将删除 yourElement.style.display 值,使其可见。
如果这是一个可观察属性,则绑定将在每次属性更改时更新可见性。否则,它只会设置一次可见性。
参数值也可以是 JavaScript 函数或返回布尔值的任意 JavaScript 表达式。DOM 元素根据输出可见或隐藏。
示例
让我们看看下面的例子。
<!DOCTYPE html>
<head>
<title>KnockoutJS Visible Binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<div data-bind = "visible: showMe">
You are seeing this line because showMe function is set to true.
</div>
<script>
function AppViewModel() {
this.showMe = ko.observable(false); // hidden initially
}
var vm = new AppViewModel();
ko.applyBindings(vm); // shown now
vm.showMe(true);
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码的工作原理 −
将上述代码保存在 visible-bind.htm 文件中。
在浏览器中打开此 HTML 文件。
knockoutjs_declarative_bindings.html

