【问题标题】:how to create a knockout hint text custom binding?如何创建敲除提示文本自定义绑定?
【发布时间】:2013-04-23 05:01:15
【问题描述】:

我正在尝试创建自定义绑定以在文本输入中显示提示文本。

到目前为止我有这个,但它不起作用:

ko.bindingHandlers.hintText= {
    init: function (element, valueAccessor) {
        element.focus(function () {
            if ($(this).val() === defaultText) {
                $(this).attr("value", "");
            }
        });
        element.blur(function () {
            if ($(this).val() === '') {
                $(this).val(valueAccessor());
            }
        });
    }
}

html:

<input id="profileID" type="text" data-bind="hintText:'Enter Profile ID'" />

【问题讨论】:

  • 你的意思是像 HTML placeholder 属性吗?
  • 是的,就像那样,但我想创建一个自定义绑定而不是使用占位符。
  • 内置的attr: {placeholder: myHintText}绑定对你有用吗?
  • 在 IE 和所有其他浏览器中都可以使用吗?

标签: knockout.js ko-custom-binding


【解决方案1】:

HTML5 placeholder 属性应该会为您完成这项工作。

如果您的浏览器要求支持 placeholder 属性,您可以使用 KnockOutJS 的 attr 绑定直接调用它,如下所示:

<input data-bind="attr:{placeholder: hintText}">

如果您需要对旧版浏览器的支持,有一个适合您的 shim:https://github.com/parndt/jquery-html5-placeholder-shim

要使用此 shim,您需要创建自定义绑定,以便在占位符更改时可以根据需要手动调用 $.placeholder.shim();

这是一个应用 shim 的“占位符”绑定(已编辑):

ko.bindingHandlers.placeholder = {
    init: function (element, valueAccessor) {
        var placeholderValue = valueAccessor();
        ko.applyBindingsToNode(element, { attr: { placeholder: placeholderValue} } );
    },
    update: function(element, valueAccessor){
        $.placeholder.shim();
    }
};

您的 html 将如下所示:

<input data-bind="placeholder: hintText">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多