1.场景:如下图,当选择定期存款时,输入框右边出现红色的必输项星号,当选择活期存款时,不再出现该星号。
2.思路一:不使用knockout,直接用click事件,就可以实现这个需求,代码如下:
<html> <head> </head> <body > <input id="Radio3" name="rdoCunKuanType" data-bind="checked:CunKuanType" onclick="document.getElementById('f1').style.display = 'inline'" value="H" checked type="radio" />活期存款 <input id="Radio4" name="rdoCunKuanType" data-bind="checked:CunKuanType" onclick="document.getElementById('f1').style.display = 'none'" value="D" type="radio">定期存款 <br />定期几年:<input type="text" />年 <font id="f1" color="red">*</font> </body> </html>
3.思路二:使用Knockout的click事件及监控属性.
代码如下:
htm
<head>
<script src=
"../lib/require/require.js"
data-main=
"ko1_radio3_main"
></script>
</head>
<body >
<input id=
"Radio3"
name=
"rdoCunKuanType"
data-bind=
"checked:CunKuanType,click:RadioClick"
value=
"H"
checked type=
"radio"
/>活期存款
<input id=
"Radio4"
name=
"rdoCunKuanType"
data-bind=
"checked:CunKuanType,click:RadioClick"
value=
"D"
type=
"radio"
>定期存款
<br />定期几年:<input type=
"text"
/>年 <font data-bind=
"visible:ShowStar"
color=
"red"
>*</font>
</body>
</html>
js
require.config({
paths: {
"knockout"
:
"../lib/knockout/knockout-2.3.0"
,
"jquery"
:
"../lib/jquery/jquery-1.9.1.min"
}
});
require([
'jquery'
,
'knockout'
],
function
($, ko) {
//数据绑定
$(document).ready(
function
() {
var
viewModel = {
CunKuanType: ko.observable(
"H"
),
ShowStar: ko.observable(
false
),
//汇往国家及地区星号显示标示符
RadioClick:
function
() {
if
(viewModel.CunKuanType() ==
"D"
) {
viewModel.ShowStar(
true
);
}
else
{
viewModel.ShowStar(
false
);
}
return
true
;
}
};
ko.applyBindings(viewModel);
});
});
需要注意的是,RadioClick最后一定要返回一个true,否则click事件无效。
4.思路三:完全不用click事件,纯粹用监控依赖属性就可以搞定.
这个最符合Knockout所主张的思想了,一个属性变了,它本身并不引发操作,而是利用监控它也就订阅它的方法自动引发操作,不必再写click了,代码如下:
htm
<html>
<head>
<script src=
"../lib/require/require.js"
data-main=
"ko1_radio1_main"
></script>
</head>
<body >
<input id=
"Radio1"
name=
"rdoCunKuanType"
data-bind=
"checked:CunKuanType"
value=
"H"
checked type=
"radio"
/>活期存款
<input id=
"Radio2"
name=
"rdoCunKuanType"
data-bind=
"checked:CunKuanType"
value=
"D"
type=
"radio"
>定期存款
<br />定期几年:<input type=
"text"
/>年 <font data-bind=
"visible:ShowStar"
color=
"red"
>*</font>
</body>
</html>
js
require.config({
paths: {
"knockout"
:
"../lib/knockout/knockout-2.3.0"
,
"jquery"
:
"../lib/jquery/jquery-1.9.1.min"
}
});
require([
'jquery'
,
'knockout'
],
function
($, ko) {
//数据绑定
$(document).ready(
function
() {
var
viewModel = {
CunKuanType: ko.observable(
"H"
)
};
viewModel.ShowStar = ko.dependentObservable(
function
()
{
if
(viewModel.CunKuanType() ==
"H"
)
{
return
false
;
}
else
{
return
true
;
}
}, viewModel);
ko.applyBindings(viewModel);
});
});