如何创建一个淘汰提示文本自定义绑定?

Xer*_*xes 1 knockout.js ko-custom-binding

我试图创建一个自定义绑定,以显示文本输入中的提示文本.

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

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());
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

html:

<input id="profileID" type="text" data-bind="hintText:'Enter Profile ID'" />
Run Code Online (Sandbox Code Playgroud)

Jos*_*iel 6

HTML5 placeholder属性应该为您完成此任务.

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

<input data-bind="attr:{placeholder: hintText}">
Run Code Online (Sandbox Code Playgroud)

如果您需要支持旧版浏览器,那么应​​该有适合您的垫片:https: //github.com/parndt/jquery-html5-placeholder-shim

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

这是一个应用垫片(编辑)的"占位符"绑定:

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

你的HTML看起来像这样:

<input data-bind="placeholder: hintText">
Run Code Online (Sandbox Code Playgroud)