<输入>淘汰赛中失去焦点/模糊事件 [英] <input> lostfocus/onblur event in knockout
问题描述
我想对可绑定到input
的可观察到的敲除事件执行一个事件.当控件失去焦点时,即使不键入任何内容,也应执行此功能.我试图更改事件绑定,但是当用户离开控件而不输入任何内容时,它不会触发.我尝试了mouseout事件,但仅在用户失去焦点后才单击,当用户单击表单中的其他位置时才触发-并不是我想要的.我希望在焦点移离控件(即使使用Tab键)时立即触发.
I want to execute an event on a knockout observable bound to an input
. This function should be executed when the control lose focus, even without typing anything. I tried to change the event binding but it doesn't fire when the user moves away from the control without typing anything. I tried mouseout event, but that only fires when the user clicks elsewhere in the form, after losing focus - not exactly what I want. I want the even to fire as soon as the focus is moved away from the control, even with tab.
以下是我用于mouseout事件的代码:
Following is the code I used for mouseout event:
<input
type="text"
id="txtFirstName"
tabindex="1"
maxlength="25"
class="txtbox"
style="width: 200px;"
data-bind="value: FirstName,
attr: {title: FirstNameErrorMessage },
css: {validationFailed: !IsValidFirstName() },
event: {mouseout: ValidateFirstName}"
/>
this.ValidateFirstName = function () {
self.IsValidFirstName(true);
self.FirstNameErrorMessage('');
if (self.FirstName() == '') {
self.IsValidFirstName(false);
self.FirstNameErrorMessage('First Name is required');
}
}
任何人都可以帮忙吗?
推荐答案
我认为您可以使用几种方法.一个不错的选择是使用KO的hasfocus
绑定: http://knockoutjs.com/documentation/hasfocus-binding.html .
I think that there are a few approaches that you could use. A nice option would be to use KO's hasfocus
binding: http://knockoutjs.com/documentation/hasfocus-binding.html.
您可以绑定可观察的布尔值,然后订阅它.在订阅中,您可以选择仅在该值现在为false时做出反应.
You can bind against a boolean observable, and then subscribe to it. In the subscription, you can choose to only react when the value is now false.
类似的东西:
self.FirstName = ko.observable();
self.FirstName.focused = ko.observable();
self.FirstName.focused.subscribe(function(newValue) {
if (!newValue) {
//do validation logic here and set any validation observables as necessary
}
});
像这样对它进行绑定
data-bind="value: FirstName, hasfocus: FirstName.focused"
我认为,如果您希望用户每次离开该字段时都触发它,而无论他们如何离开该字段以及是否实际进行了更改,这都是一个不错的选择.
I think that this would be a good option if you want it to fire everytime a user leaves the field no matter how they leave it and regardless of whether a change was actually made.
这篇关于<输入>淘汰赛中失去焦点/模糊事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!