具有“只读"和“已禁用"等属性的淘汰赛属性绑定 [英] Knockout attr binding with attributes like 'readonly' and 'disabled'

查看:23
本文介绍了具有“只读"和“已禁用"等属性的淘汰赛属性绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Knockout 的attr"数据绑定以及 readonly"disabled"等独立属性的建议最佳实践"方法是什么>?

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"数据绑定确实支持这种情况,只需从您的 nullundefined>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.

演示 Fiddle.

这篇关于具有“只读"和“已禁用"等属性的淘汰赛属性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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