難道你不只是使用hasFocus數據綁定?
https://jsfiddle.net/0o89pmju/52/
點擊清脆的名字按鈕,驗證將失敗。並且自動對焦將被設置爲名字。
我不太以下你的擴展,所以我用了一個需要從文檔http://knockoutjs.com/documentation/extenders.html
HTML
<p data-bind="css: { error: firstName.hasError }">
<input data-bind='value: firstName, valueUpdate: "afterkeydown", hasFocus: firstName.hasError' />
<span data-bind='visible: firstName.hasError, text: firstName.validationMessage'> </span>
</p>
<p data-bind="css: { error: lastName.hasError }">
<input data-bind='value: lastName, valueUpdate: "afterkeydown"' />
<span data-bind='visible: lastName.hasError, text: lastName.validationMessage'> </span>
</p>
<p>
<button data-bind="click: clearName">clear first name</button>
</button>
</p>
JS
ko.extenders.required = function(target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
function AppViewModel(first, last) {
var self = this;
this.firstName = ko.observable(first).extend({
required: "Please enter a first name"
});
this.lastName = ko.observable(last).extend({
required: ""
});
this.clearName = function() {
self.firstName('');
self.lastName('');
}
}
ko.applyBindings(new AppViewModel("Bob", "Smith"));
self.FirstName = ko.observable(報告.OverallRetention).extend({reportValueChange:{property:firstName}}); ko.extenders.reportValueChange = function(target,option){ debugger; var _oldValue; target.setFocus = function(val){ target.hasfocus = val; }; target.subscribe(function(oldValue){oldValue = oldValue; },null,'beforeChange'); target.subscribe(function(newValue){ ///////想在此處設置焦點 } – ALI