如何使用knockout.js焦点设置由绑定到数组的模板创建的元素?
我有一个绑定到表的可观察数组,其中每一行都是一组输入元素,以允许编辑数组元素的属性.底部是一个"Add"按钮,它将一个新元素推入数组,创建一个新的输入字段行.
我要做的是"Add"在按下按钮后将焦点设置为新创建的输入字段中的第一个.
HTML:
<html>
<head>
<script src="http://cdn.jsdelivr.net/knockout/3.0.0/knockout.debug.js"></script>
</head>
<body>
<table data-bind='foreach: Attributes'>
<tr>
<td><input type='text' data-bind='value: Name, disable: HardCoded/></td>
<td><input type='text' data-bind='value: Description'/></td>
<td><button data-bind="click: $parent.removeAttribute">Delete</button></td>
</tr>
</table>
<button data-bind="click: addAttribute">Add attribute</button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
function Attribute(id, name, description, hardcoded) {
var self=this;
self.AttributeID=ko.observable(id || 0);
self.Name=name || '';
self.Description=description || '';
self.HardCoded=hardcoded || false;
self.nameFocus = true;
}
function AttributeSchema(attributeArray) {
var self=this;
// Properties
self.Attributes=ko.observableArray(attributeArray);
// Operations
self.addAttribute=function() {
self.Attributes.push(new Attribute());
};
self.removeAttribute=function() {
self.Attributes.remove(this);
};
}
var vmSchema=new AttributeSchema(
[
new Attribute(5, 'FirstName', 'First Name', true),
new Attribute(6, 'LastName', 'Last Name', true),
new Attribute(7, 'Blah', 'Blah', false)
]
);
ko.applyBindings(vmSchema);
Run Code Online (Sandbox Code Playgroud)
Vla*_*lik 19
目前,您有这样的代码:
<input type='text' data-bind='value: Name, disable: HardCoded' />
Run Code Online (Sandbox Code Playgroud)
您可以尝试添加该属性hasfocus: true:
<input type='text' data-bind='value: Name, disable: HardCoded, hasfocus: true' />
Run Code Online (Sandbox Code Playgroud)
请参阅:http://knockoutjs.com/documentation/hasfocus-binding.html
| 归档时间: |
|
| 查看次数: |
11167 次 |
| 最近记录: |