Html 具有“只读”和“禁用”等属性的淘汰赛属性绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14165213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Knockout attr binding with attributes like 'readonly' and 'disabled'
提问by Armchair Bronco
What's the suggested "best practice" way to use Knockout's "attr" data bindingwith standalone attributes like "readonly"and "disabled"?
将Knockout 的“attr”数据绑定与“readonly”和“disabled”等独立属性一起使用的建议“最佳实践”方式是什么?
These attributes are specialin 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):
这些属性的特殊之处在于它们通常通过将属性值设置为属性名称来启用(尽管如果您在 HTML 中仅包含属性名称而不包含任何值,则许多浏览器可以正常工作):
<input type="text" readonly="readonly" disabled="disabled" value="foo" />
However, if you don'twant 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"):
但是,如果你不做要应用这些属性,一般的做法是简单地忽略通通从HTML(而不是做这样的事情只读=“假”):
<input type="text" value="foo" />
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:
Knockout 的“attr”数据绑定不支持这种情况。一旦我提供了一个属性名称,我还需要提供一个值:
<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 bindingthat I can use to not render anythingif I don't want the item disabled or made read-only?
是否有跨浏览器的方式关闭“禁用”或“只读”?或者是否有自定义绑定的技巧,如果我不希望该项目被禁用或设为只读,我可以使用它来不呈现任何内容?
回答by nemesv
回答by Greg Gum
You can also create a binding for readonly like this:
您还可以像这样创建只读绑定:
ko.bindingHandlers['readonly'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (!value && element.readOnly)
element.readOnly = false;
else if (value && !element.readOnly)
element.readOnly = true;
}
};