KnockoutJS 3.X API 第四章 数据绑定(1) 文本及样式绑定
目录
本节将介绍六种文本绑定方式:
visible绑定text绑定html绑定css绑定style绑定attr绑定
可见文本绑定(visible)
使用visible绑定,来控制DOM元素的可见或隐藏
例子:
<div data-bind="visible: shouldShowMessage">
You will see this message only when "shouldShowMessage" holds a true value.
</div> <script type="text/javascript">
var viewModel = {
shouldShowMessage: ko.observable(true) // Message initially visible
};
viewModel.shouldShowMessage(false); // ... now it's hidden
viewModel.shouldShowMessage(true); // ... now it's visible again
</script>
参数:
主要技术参数
当参数解析为假(例如,布尔值
false,或数字值0,或者null,或undefined),则当前元素隐藏,如同CSS样式中display:none。当参数解析为真(例如,布尔值
true,或者一个非null对象或序列)中,使其成为可见的。
使用函数和表达式来控制元素的可见性
您还可以使用JavaScript函数或任意JavaScript表达式作为参数值,KO将运行你的函数/表达式,并使用结果来确定是否隐藏元素。
例如:
<div data-bind="visible: myValues().length > 0">
You will see this message only when 'myValues' has at least one member.
</div> <script type="text/javascript">
var viewModel = {
myValues: ko.observableArray([]) // Initially empty, so message hidden
};
viewModel.myValues.push("some value"); // Now visible
</script>
文本绑定(text)
使用text绑定到相关的DOM,以显示视图模型属性的值。可用于任何DOM元素上
例如:
Today's message is: <span data-bind="text: myMessage"></span> <script type="text/javascript">
var viewModel = {
myMessage: ko.observable() // Initially blank
};
viewModel.myMessage("Hello, world!"); // Text appears
</script>
使用函数和表达式来作为文本值
例如:
The item is <span data-bind="text: priceRating"></span> today. <script type="text/javascript">
var viewModel = {
price: ko.observable(24.95)
};
viewModel.priceRating = ko.pureComputed(function() {
return this.price() > 50 ? "expensive" : "affordable";
}, viewModel);
</script>
也可以写为如下等同格式:
The item is <span data-bind="text: price() > 50 ? 'expensive' : 'affordable'"></span> today.
HTML编码
在给视图属性赋值时,默认KO时进行HTML编码的,也就是说,如果赋值的是带有DOM标记或者JS脚本的值,一律会原封不动的显示。不会造成安全隐患或脚本注入等情况。
例如:
viewModel.myMessage("<i>Hello, world!</i>");
只会显示<i>Hello,workld!</i>,而不是斜体文本hello world
使用无容器的text绑定
在某些情况下,可能不允许在UI中加入新的dom元素作为KO的text绑定容器,比如下边的这个例子,如果在option元素中再加入新的span元素,将导致无法正常工作:
<select data-bind="foreach: items">
<option>Item <span data-bind="text: name"></span></option>
</select>
在这种情况中,可以使用ko自带的无容器绑定写法:<!--ko--> 和 <!--/ko-->,使用这种写法,ko会虚拟出一个容器元素作为绑定使用。
<select data-bind="foreach: items">
<option>Item <!--ko text: name--><!--/ko--></option>
</select>
HTML绑定
次绑定方式主要用于显示HTML相关的DOM元素,具体的讲就是将包含HTML元素的视图模型属性渲染到UI上。例如:
<div data-bind="html: details"></div> <script type="text/javascript">
var viewModel = {
details: ko.observable() // Initially blank
};
viewModel.details("<em>For further details, view the report <a href='report.html'>here</a>.</em>"); // HTML content appears
</script>
这种方式要注意的是脚本注入攻击,切勿将该方式用于用户输入。
CSS绑定
目的:
CSS绑定主要用于对DOM元素的CSS类添加或删除,这种方式是很有用的,当然Jquery也能做到这一点。
静态例子:
<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div>
<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially we don't apply the "profitWarning" class
};
viewModel.currentProfit(-50); // Causes the "profitWarning" class to be applied
</script>
上述例子意思是,当视图属性currentProfit小于0时,将移除div元素的profitWarning的css类。
动态例子:
<div data-bind="css: profitStatus">
Profit Information
</div> <script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000)
}; // Evalutes to a positive value, so initially we apply the "profitPositive" class
viewModel.profitStatus = ko.pureComputed(function() {
return this.currentProfit() < 0 ? "profitWarning" : "profitPositive";
}, viewModel); // Causes the "profitPositive" class to be removed and "profitWarning" class to be added
viewModel.currentProfit(-50);
</script>
上述例子的意思是,当currentProfit视图属性值小于0时,div元素的添加css类profitWarning,否则添加css类profitPositive。
注意:
你可以设置一个或多个CSS绑定,来实现多个绑定需求:
<div data-bind="css: { profitWarning: currentProfit() < 0, majorHighlight: isSevere }">
你甚至也可以用引号把CSS类名括起来:
<div data-bind="css: { profitWarning: currentProfit() < 0, 'major highlight': isSevere }">
在视图模型属性返回值中,0与null被视为false,非null或非零的值被视为true。
如果视图模型属性是一个监控属性类型(observable),那么之后的css绑定将根据模型属性的值变化而变化,如果你的视图模型属性不是一个监控属性,那只有第一次运行会变化,之后将不会改变。在动态CSS绑定中同样适用该规则。
二次注意:
如果你要添加的CSS类名是my-class,如果你像下边这种写法的话,将没有效果
<div data-bind="css: { my-class: someValue }">...</div>
因为my-class这种名字是不合法的在KO的CSS绑定中,解决这个问题最简单的方法是加上引号:
<div data-bind="css: { 'my-class': someValue }">...</div>
Style绑定
目的:
style绑定与CSS绑定类似,只是style绑定是添加或删除一个或多个元素样式,例如:
<div data-bind="style: { color: currentProfit() < 0 ? 'red' : 'black' }">
Profit Information
</div>
<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially black
};
viewModel.currentProfit(-50); // Causes the DIV's contents to go red
</script>
上述例子是将div元素的color样式赋值,当currentProfit视图模型属性的值小于0时,赋值red,否则赋值black;
与CSS绑定一样,style绑定也支持多个参数同时绑定。比如:
<div data-bind="style: { color: currentProfit() < 0 ? 'red' : 'black', fontWeight: isSevere() ? 'bold' : '' }">...</div>
如果视图模型属性是一个监控属性类型(observable),那么之后的style绑定将根据模型属性的值变化而变化,如果你的视图模型属性不是一个监控属性,那只有第一次运行会变化,之后将不会改变。
注意:
如果你需要绑定一些style,例如font-weight或者text-decoration
- 不要写成这样
{ font-weight: someValue }; 要写成这样{ fontWeight: someValue } - 不要写成这样
{ text-decoration: someValue }; 要写成这样{ textDecoration: someValue }
更多的Style绑定的KO写法请点击这个地址查看
attr绑定
目的:
attr绑定主要是为了通过KO设置元素的值,比如img标签的src值,a标签的href值和title值。例如:
<a data-bind="attr: { href: url, title: details }">
Report
</a>
<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>
上述例子将设置DOM上a标签的href为year-end.html,设置a标签的title为Report including final year-end statistics。
注意:
如果你像更改元素的data-something属性的值时,不可以写成下main这样:
<div data-bind="attr: { data-something: someValue }">...</div>
因为data-something是KO中不合法的标识名称。最简单的方法是用引号括住:
<div data-bind="attr: { 'data-something': someValue }">...</div>
KnockoutJS 3.X API 第四章 数据绑定(1) 文本及样式绑定的更多相关文章
- KnockoutJS 3.X API 第四章 数据绑定(5) 控制流component绑定
本节目录: 一个例子 API 备注1:仅模板式的component 备注2:component虚拟绑定 备注3:传递标记到component绑定 内存管理 一个例子 First instance, w ...
- KnockoutJS 3.X API 第四章 数据绑定(2) 控制流foreach绑定
foreach绑定 foreach绑定主要用于循环展示监控数组属性中的每一个元素,一般用于table标签中 假设你有一个监控属性数组,每当您添加,删除或重新排序数组项时,绑定将有效地更新UI的DOM- ...
- KnockoutJS 3.X API 第四章 数据绑定(3) 控制流if绑定和ifnot绑定
if绑定目的 if绑定一般是格式是data-bind=if:attribute,if后所跟属性或表达式的值应为bool值(也可以是非bool值,当非空字符串时则为真),if绑定的作用与visible绑 ...
- KnockoutJS 3.X API 第四章 数据绑定(4) 控制流with绑定
with绑定的目的 使用with绑定的格式为data-bind="with:attribute",使用with绑定会将其后所跟的属性看作一个新的上下文进行绑定.with绑定内部的所 ...
- KnockoutJS 3.X API 第四章(13) template绑定
目的 template绑定(模板绑定)使用渲染模板的结果填充关联的DOM元素. 模板是一种简单方便的方式来构建复杂的UI结构 . 下面介绍两种使用模板绑定的方法: 本地模板是支持foreach,if, ...
- KnockoutJS 3.X API 第四章 表单绑定(11) options绑定
目的 options绑定主要用于下拉列表中(即<select>元素)或多选列表(例如,<select size='6'>).此绑定不能与除<select>元素之外的 ...
- KnockoutJS 3.X API 第四章 表单绑定(6) click绑定
目的 click绑定主要作用是用于DOM元素被点击时调用相关JS函数.最常见用于button.input.a元素. 例如: You've clicked timesClick me var viewM ...
- KnockoutJS 3.X API 第四章 表单绑定(7) event绑定
目的 event绑定即为事件绑定,即当触发相关DOM事件的时候回调函数.例如keypress,mouseover或者mouseout等 例如: Mouse over me Details var vi ...
- KnockoutJS 3.X API 第四章 表单绑定(8) submit、enable、disable绑定
submit绑定目的 submit绑定即为提交绑定,通常用于form元素.这种绑定方式会打断默认的提交至服务器的操作.转而提交到你设定好的提交绑定回调函数中.如果要打破这个默认规则,只需要在回调函数中 ...
随机推荐
- 提取c#代码文件中的方法块
此方法是取C#文件里面的方法块,并删除缩进符,感觉写得还是比较容易懂的,所以收藏下,以便将来用到. private static string GetCodeBlock(string allCo ...
- Core Audio(二)
用户模式音频组件 在windows vista中,core audio apis充当用户模式音频子系统的基础,core audio apis作为用户模式系统组件的一个thin layer,它用来将用户 ...
- Make Notepad++ auto close HTML/XML tags after the slash(the Dreamweaver way)
I've been looking for a Notepad++ plugin that can close HTML/XML tags after a slash just like the wa ...
- python多线程的用法之一
import threadingimport time class thread_1(threading.Thread): sleep_time = 0 def __init__(self,id1): ...
- coding.net
http://coding.net 看上去不错,简洁自然. https://coding.net/u/zhongzf/p/TestProject/git http://zhongzf.coding.i ...
- mongoDB研究笔记:分片集群部署
前面几篇文章的分析复制集解决了数据库的备份与自动故障转移,但是围绕数据库的业务中当前还有两个方面的问题变得越来越重要.一是海量数据如何存储?二是如何高效的读写海量数据?尽管复制集也可以实现读写分析,如 ...
- [后端人员耍前端系列]AngularJs篇:30分钟快速掌握AngularJs
一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用 ...
- 3年的坚持,最终造就著作——《Learninghard C#学习笔记》
前言 起初开始写博文主要是记录学习过程中对学到内容的自我总结和理解,同时也希望本人的理解可以帮助到一些走在学习路上的朋友.但是令我没有想到的是,我总结的博文得到了广大园友的评论和支持,正是博友的支持, ...
- WPF 编辑状态切换
有时候DataGrid编辑的时候一个属性需要根据别的属性呈现不同的编辑状态.这就需要一个做一个状态切换.比如地址是1的时候,读写类型是读写.只读.只写.地址是2的时候,就只读.状态栏切换为TextBo ...
- 【吉光片羽】MVC 导出Word的两种方式
1.直接将Html转成Word.MVC自带FileResult很好用.Html中我们也可以嵌入自己的样式. html: <div id="target"> <st ...