我想在用户按钮单击时显示错误消息(以防用户打开页面并直接单击按钮)。但是只有在用户编辑字段时可见状态才起作用如何触发方法来更改可见状态?
<body>
<input type="text" data-bind="value: can" id="txtcan" />
<span ID="lblCANerror" data-bind="visible:(viewModel.can()=='')" class="error">Mesasage 1</span>
<input type="text" data-bind="value: login" id="txtusername" />
<span ID="lblUsernameError" data-bind="visible:(viewModel.login()=='')" class="error">Mesasage 2</span>
<input type="password" data-bind="value: password" name="txtpassword" />
<span ID="lblPasswordError" data-bind="visible:(viewModel.password()=='')" class="error">Mesasage 3</span>
<button ID="lnkLogin" data-bind="click: ClickBtn"> Click</button>
</body>
<script type='text/javascript'>
var ViewModel = function () {
this.can = ko.observable();
this.login = ko.observable();
this.password = ko.observable();
this.isValidForm = ko.computed(function () {
return ($.trim(this.can) != "") && ($.trim(this.login) != "") && ($.trim(this.password) != "");
}, this);
this.ClickBtn = function(data, e)
{
if (!this.isValidForm())
{
e.stopImmediatePropagation();
};
};
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
</script>
<style type='text/css'>
.error
{
color: #FF0000;
}
</style>
我不想编写手动更改跨度可见状态的代码(例如 if () 然后 span.show)是否可以仅使用 knockoutjs FW ?我试过用 JQuery 订阅事件,但结果是一样的。
$().ready(function () {
$("#lnkLogin").click(function (event) {
if (!viewModel.isValidForm()) {
event.preventDefault();
};
})
});
谢谢。