淘汰赛 js ->绑定到可编辑的 div 文本? [英] Knockout js -> Bind to editable div text?

查看:22
本文介绍了淘汰赛 js ->绑定到可编辑的 div 文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 observable 绑定到可编辑的 div 文本内容?

How can I bind an observable to an editable div text content?

推荐答案

您需要修改默认的文本"绑定,以便能够将编辑过的 div 的内容写回可观察对象.此任务的简单自定义绑定处理程序如下所示:

You will need to modify the default "text" binding so that it is able to write the content of the edited div back to the observable. A simple custom binding handler for this task can look like this:

ko.bindingHandlers.editableText = {
    init: function(element, valueAccessor) {
        $(element).on('blur', function() {
            var observable = valueAccessor();
            observable( $(this).text() );
        });
    },
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).text(value);
    }
};

但请注意,此示例代码需要 jQuery.

But please note that this example code requires jQuery.

使用就这么简单:

<div contentEditable="true" data-bind="editableText: foo"></div>

这是一个例子(用 CoffeeScript 编写):http://jsfiddle.net/aBUEu/1/

Here is an example (written in CoffeeScript): http://jsfiddle.net/aBUEu/1/

这篇关于淘汰赛 js ->绑定到可编辑的 div 文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆