Knockout.js hasfocus实现在动态添加的行上 [英] knockoutjs hasfocus implementation on dynamically added row
问题描述
我有一个数据表,该数据表是KO中可观察到的数据.当您跳出最后一行的最后一个输入时,它会添加另一行输入,以便您可以输入新数据.最初应该将焦点放在第一个输入上.当该输入模糊时,它将运行一些检查.如果这些检查中的任何一个失败,我想显示一条消息(当前正在工作),并将焦点发送回该输入.我不知道该如何找回焦点.
I have a table of data that is an observable of observables in KO. When you tab out of the last input of the last row, it adds an additional row of inputs so you can type in new data. It is supposed to initially put the focus in the first input. When that input is blurred, it runs some checks. If any of those checks fail, I want to show a message(currently working) and sent the focus back to that input. I cannot figure out how to get that focus back.
以下是相关的HTML代码段:
Here is the relevant HTML snippet:
<tbody data-bind="foreach: items">
<tr>
<td>
<div data-bind="if: (itemNo.length < 1)"><input data-bind="value: itemNo, hasFocus: $parent.invalidItem, event: { blur: $parent.checkItemNo }, attr: { name: 'brochureitems[' + $index() + '].itemNo', id: 'brochureItems_' + $index() + '__itemNo' }, validationOptions: { errorElementClass: 'input-validation-error' }" class="form-control item-id" /></div>
这是我的淘汰赛代码:
var itemsModel = function(items) {
var self = this;
self.items = ko.observableArray(items);
self.invalidItem = ko.observable(true);
self.checkItemNo = function(data) {
self.invalidItem(false);
console.log(data);
var itemNo = $.trim(data.itemNo());
if (itemNo != "") {
var item = "";
$.each(window.listOfItems, function(i, v) {
if (v.No.search(itemNo) != -1) {
item = v.Description;
return;
}
});
if(item != "") {
var match = ko.utils.arrayFirst(self.items, function(item) {
return itemNo === item.itemNo;
});
if (!match) {
data.itemDesc(item);
}
} else { // invalid item #
slideDownMsg("Invalid item number.");
slideUpMsg(3000);
self.invalidItem(true);
}
}
}
self.submit = function() {
//self.showErrors(true);
if (viewModel.errors().length === 0) {
console.log('Thank you.');
$("#brochureForm").submit();
}
else {
console.log('Please check your submission.');
viewModel.errors.showAllMessages();
$(".input-validation-error").first().focus();
}
}
self.addLine = function() {
self.items.push( new itemModel() );
};
self.insertLine = function(index) {
self.items.splice(index, 0, new itemModel() );
};
self.removeItem = function(item) {
self.items.remove(item);
};
self.errors = ko.validation.group(self.items, { deep: true, live: true });
self.validate = function() {
self.errors.showAllMessages();
}
};
很明显,我遗漏了很多代码,但希望这足以显示我的问题.
Obviously, I left a lot of code out, but hopefully this is enough to show my issue.
推荐答案
请参见 https://stackoverflow.com/a/4186003/1287183
使用setTimeout
setTimeout(function() { self.invalidItem(true); }, 1);
此外,您可以在checkItemNo
中取出self.invalidItem(false);
.
Also, you can take out self.invalidItem(false);
in checkItemNo
.
这篇关于Knockout.js hasfocus实现在动态添加的行上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!