gpt4 book ai didi

使用 Knockout.js 选择()输入字段

转载 作者:行者123 更新时间:2023-12-02 06:12:00 27 4
gpt4 key购买 nike

我是 Knockout.js 的新手。

访问 select()最佳方式是什么?一个<input />当它变得可见时?

查看:

<p>
Name:
<b data-bind="visible: !editing(), text: name, click: edit">&nbsp;</b>
<input data-bind="visible: editing, value: name, hasfocus: editing" />
</p>

View 模型:

function PersonViewModel(name) {
// Data
this.name = ko.observable(name);
this.editing = ko.observable(false);

// Behaviors
this.edit = function() { this.editing(true) }
}

ko.applyBindings(new PersonViewModel("Bert Bertington"));

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

http://jsfiddle.net/RnCUd/

谢谢!

最佳答案

您可以创建一个新的绑定(bind)来处理选择。

ko.bindingHandlers.selected = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var selected = ko.utils.unwrapObservable(valueAccessor());
if (selected) element.select();
}
};

将此绑定(bind)添加到您的输入字段。

<input data-bind="visible: editing, value: name, hasfocus: editing, selected: editing" />

这是一个 fiddle :http://jsfiddle.net/RnCUd/2/

<小时/>

或者,您可以创建一个包装 hasfocus 绑定(bind)的自定义绑定(bind):

ko.bindingHandlers.hasSelectedFocus = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.bindingHandlers['hasfocus'].init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
},
update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
ko.bindingHandlers['hasfocus'].update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);

var selected = ko.utils.unwrapObservable(valueAccessor());
if (selected) element.select();
}
};

此绑定(bind)只是将初始化和更新委托(delegate)给 hasfocus,并在可观察值为 true 时负责选择元素。使用它代替 hasfocus

<input data-bind="visible: editing, value: name, hasSelectedFocus: editing" />

这是一个 fiddle :http://jsfiddle.net/RnCUd/1/

关于使用 Knockout.js 选择()输入字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12294847/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com