javascript 点击后 Knockout.js 输入焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16787297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:59:48  来源:igfitidea点击:

Knockout.js input focus after click

javascriptknockout.jsknockout-2.0

提问by tugberk

I am trying to set focus on an input with knockout after the click event is fired but couldn't find a clean way to handle it without coupling with the DOM. Here is the JS code I have:

我试图在点击事件被触发后将焦点设置在敲除的输入上,但找不到一种干净的方法来处理它而不与 DOM 耦合。这是我拥有的JS代码:

(function() {

    var vm = {
        text: ko.observable(),
        items: ko.observableArray([])
    }

    vm.addItem = function() { 
        vm.items.push(vm.text());
        vm.text(null);
    }

    ko.applyBindings(vm);

}());

This is my DOM:

这是我的 DOM:

<input type="text" data-bind="value: text" />
<a href="#" data-bind="click: addItem">Send</a>

<ul data-bind="foreach: items">
    <li data-bind="text: $data"></li>
</ul>

Here is the JsFiddle sample: http://jsfiddle.net/srJUa/1/

这是 JsFiddle 示例:http: //jsfiddle.net/srJUa/1/

What I want it to set focus on the input after the vm.addItemis completed. Any idea how this can be done cleanly, for example with a custom knockout binding?

我希望它在vm.addItem完成后将焦点设置在输入上。知道如何干净利落地做到这一点,例如使用自定义淘汰赛绑定吗?

回答by nemesv

Knockout has a built-in binding for manipulating the focus: The "hasfocus" binding.

Knockout 具有用于操作焦点的内置绑定:“hasfocus”绑定

So you just need to create a boolean property on your viewmodel and bind it on your input and set the property to trueif you want to focus the input.

因此,您只需要在您的视图模型上创建一个布尔属性并将其绑定到您的输入并将该属性设置为true是否要聚焦输入。

Or in your case you can binding directly to your textproperty, so when it is does not have any text it should has the focus:

或者在您的情况下,您可以直接绑定到您的text属性,因此当它没有任何文本时,它应该具有焦点:

<input type="text" data-bind="value: text, hasfocus: !text()" />

Demo JSFiddle.

演示JSFiddle

回答by tugberk

OK, I have solved the issue by leveraging the hasfocus binding:

好的,我已经通过利用 hasfocus 绑定解决了这个问题:

(function() {

    var vm = {
        text: ko.observable(),
        items: ko.observableArray([]),
        isFocused: ko.observable()
    }

    vm.addItem = function() { 
        vm.items.push(vm.text());
        vm.text(null);
        vm.isFocused(true);
    }

    ko.applyBindings(vm);

}());

HTML:

HTML:

<input type="text" data-bind="value: text, hasfocus: isFocused" />
<a href="#" data-bind="click: addItem">Send</a>

<ul data-bind="foreach: items">
    <li data-bind="text: $data"></li>
</ul>

Working sample: http://jsfiddle.net/srJUa/2/

工作示例:http: //jsfiddle.net/srJUa/2/

Not sure if this is the best way, though.

不过,不确定这是否是最好的方法。