更新“占位符"使用淘汰赛的属性 [英] updating "placeholder" attribute using knockout

查看:30
本文介绍了更新“占位符"使用淘汰赛的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些字段的表单,使用 Knockout.js(2.1.0 版)获取一些数据.例如,要更新我输入的值"字段:

I have a form with some fields getting some data using knockout.js (ver. 2.1.0). For example, to update the "value" field of an input I put:

<input type="text"  name="contrasena" id="login-user" value="" placeholder="" data-bind="value: user">

我有一个 JSON 来存储我想用于pass"关键字的值,并且它可以正常工作.

I have a JSON to store the value a I want to use for "pass" keyword, and it works correctly.

我尝试使用相同的方法设置占位符"属性,但它不起作用:

I tried to set "placeholder" attribute using the same method, but it doesn't works:

<input type="text"  name="contrasena" id="login-user" placeholder="" data-bind="placeholder: user">

我试图修改knockout.js文件,添加基于ko.bindingHandlers['value']"的ko.bindingHandlers['placeholder']"函数(在ko.jsonExpressionRewriting"中修改placeholder"而不是value").writeValueToProperty"函数),但它不能正常工作,它将信息放在值"属性而不是占位符"中.

I tried to modify knockout.js file adding "ko.bindingHandlers['placeholder']" function based on "ko.bindingHandlers['value']" (modifying "placeholder" instead of "value" in "ko.jsonExpressionRewriting.writeValueToProperty" function), but it doesn't work correctly, it puts the information in "value" attribute instead of "placeholder".

有人知道解决这个问题的方法吗?

Anyone knows the way to solve this?

非常感谢!

推荐答案

如果你想使用data-bind="placeholder: user",你可以创建一个自定义绑定 在您的 js 代码中.

If you want to use data-bind="placeholder: user", you can create a custom-binding in your js code.

您使用 ko.bindingHandlers['placeholder'] 走在正确的道路上,但您不需要编辑 Knockout.js 文件 ——事实上,这是不好的做法.

You were on the right path using ko.bindingHandlers['placeholder'] but you don't need to edit the knockout.js file -- in fact, that is bad practice.

这需要一个非常基本的自定义绑定:

This would require a very basic custom-binding:

ko.bindingHandlers.placeholder = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var underlyingObservable = valueAccessor();
        ko.applyBindingsToNode(element, { attr: { placeholder: underlyingObservable } } );
    }
};

有关自定义绑定的指南,请参阅 这里

For a guide on custom-bindings, see here

虽然 Knockout 本身就很突兀,但稍微少了一些.它从视图中删除了如何将占位符应用于元素的知识.

Although Knockout is itself inherently obtrusive, this is slightly less. It removes the knowledge of how the placeholder is applied to the element from the view.

事实上,如果将来你想应用某种 jQuery 插件来在不支持 placeholder 属性的浏览器中显示占位符,这就是地方 (init:) 来初始化插件——在这种情况下你还需要一个 update: 函数.

In fact, if in the future you wanted to apply some sort of jQuery plugin to show placeholders in browsers which don't support the placeholder attribute, this would be the place (init:) to initialise the plugin -- you would also need an update: function in that case.

这篇关于更新“占位符"使用淘汰赛的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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