Knockout attr与“readonly”和“disabled”等属性绑定 [英] Knockout attr binding with attributes like 'readonly' and 'disabled'

查看:1182
本文介绍了Knockout attr与“readonly”和“disabled”等属性绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Knockout的attr数据绑定与独立属性(例如readonlydisabled?

What's the suggested "best practice" way to use Knockout's "attr" data binding with standalone attributes like "readonly" and "disabled"?

这些属性是特殊,因为它们通常通过将属性值设置为属性名来启用(尽管许多浏览器可以正常工作您只需在HTML中包含不带任何值的属性名称):

These attributes are special in that they are generally enabled by setting the attribute value to the attribute name (although many browsers work fine if you simply include the attribute names without any values in the HTML):

<input type="text" readonly="readonly" disabled="disabled" value="foo" />

但是,如果希望应用这些属性,一般的做法是从HTML中完全省略它们(而不是像readonly =false)这样做:

However, if you don't want these attributes to be applied, the general practice is to simply omit them altogether from the HTML (as opposed to doing something like readonly="false"):

<input type="text" value="foo" />

Knockout的attr数据绑定不支持此方案。一旦我提供属性名称,我也需要提供一个值:

Knockout's "attr" data binding doesn't support this scenario. As soon as I provide an attribute name, I need to provide a value as well:

<input type="text" data-bind="attr: { 'disabled': getDisabledState() }" />

是否有跨浏览器方式关闭禁用或只读?或者,如果我不想让项目被禁用或是只读的,那么我可以使用自定义绑定的技巧来不渲染任何

Is there a cross-browser way turn off 'disabled' or 'readonly'? Or is there a trick with a custom binding that I can use to not render anything if I don't want the item disabled or made read-only?

推荐答案

Knockout的attr数据绑定确实支持这种情况,只需返回 null undefined 从您的 getDisabledState()函数,那么它不会发出属性。

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.

演示小提琴

这篇关于Knockout attr与“readonly”和“disabled”等属性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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