【问题标题】:knockout.js set focus in a templateknockout.js 在模板中设置焦点
【发布时间】:2012-02-26 09:35:18
【问题描述】:

如何使用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>

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);

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    目前,你有这样的代码:

    <input type='text' data-bind='value: Name, disable: HardCoded' />
    

    您可以尝试添加属性hasfocus: true

    <input type='text' data-bind='value: Name, disable: HardCoded, hasfocus: true' />
    

    见:http://knockoutjs.com/documentation/hasfocus-binding.html

    【讨论】:

    • 非常感谢,完美的答案! Knockout.js 摇滚!
    【解决方案2】:

    我有一个字段,其可见性由复选框确定,我希望该字段在可见后立即获得焦点。使用默认的 hasfocus 绑定意味着该字段在失去焦点后立即隐藏。

    为了解决这个问题,我创建了一个“单向”有焦点绑定,如下所示:

    ko.bindingHandlers.koFocus = {
        update: function (element, valueAccessor) {
            var value = valueAccessor();
            var $element = $(element);
                if (value()) {
                    $element.focus();
                }
        }
    };
    

    然后我换了:

    data-bind="hasfocus: myObservable" 
    

    与:

    data-bind="koFocus: myObservable"
    

    问题解决了

    【讨论】:

    • 我解开了 valueAccessor,这样我也可以传入 !myObservable():var value = ko.unwrap(valueAccessor()); 然后检查 if(value) 而不是 if(value())
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多