问题: 我有一个自定义数字键盘和一个包含QTY输入的动态表。我的问题是,为了将触摸数字的值分配给在触及任何数字之前具有焦点的随机QTY输入,最佳方法是什么?
示例 https://jsfiddle.net/kyr6w2x3/166/
HTML:
<table class="table ">
<thead>
<tr>
<th class="text-center">Item</th>
<th class="text-center">Qty</th>
</tr>
</thead>
<tbody data-bind="foreach:ListOfScannedItems">
<tr>
<td><input type="text" class="form-control" placeholder="" data-bind="textInput:Item"></td>
<td><input type="number" class="form-control" data-bind="textInput:Quantity" /></td>
</tr>
</tbody>
</table>
<input type="text" class="form-control margin-top-5" placeholder="type something" data-bind="textInput:scanItemInput">
<input type="button" data-bind="click:AddItem" value="Add">
<ul id="keyboard">
<li class="symbol" data-bind="click: function() {keybordClicked(1)}"><span class="off">1</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(2)}"><span class="off">2</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(3)}"><span class="off">3</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(4)}"><span class="off">4</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(5)}"><span class="off">5</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(6)}"><span class="off">6</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(7)}"><span class="off">7</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(8)}"><span class="off">8</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(9)}"><span class="off">9</span></li>
<li class="symbol" data-bind="click: function() {keybordClicked(0)}"><span class="off">0</span></li>
<li class="delete lastitem" data-bind="click: function() {keybordClicked(-1)}">⌫</li>
</ul>
VM:
var appVM = function(){
var self = this;
self.scanItemInput = ko.observable();
self.ListOfScannedItems = ko.observableArray([]);
self.AddItem = function () {
self.ListOfScannedItems.push(new ScannedItemVM({ Item: self.scanItemInput()}));
self.scanItemInput("");
}
self.keybordClicked = function(value){
console.log(value);
// how to assign this value to the input that has focused before pressing on any number
}
}
var ScannedItemVM = function (data) {
var self = this;
self.Item = ko.observable(data.Item);
self.Quantity = ko.observable("");
}
var vm = new appVM();
ko.applyBindings(vm);
答案 0 :(得分:1)
您可以对扫描的项目输入使用模糊事件绑定来跟踪哪个控件最后关注。
<input type="number" class="form-control" data-bind="textInput:Quantity, event: {blur: $parent.onBlur}" />
...
self.lastFocused = ko.observable();
self.onBlur = function(data, event){
self.lastFocused(data);
}
然后,当您单击键盘时,您可以更新该输入的视图模型的数量。
self.keybordClicked = function(value){
console.log(value);
// how to assign this value to the input that has focused before pressing on any number
//console.log(self.ListOfScannedItems()[0].HasFocus());
self.lastFocused().Quantity(value);
}