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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 04:44:42  来源:igfitidea点击:

Knockout attr binding with attributes like 'readonly' and 'disabled'

htmldata-bindingknockout.jsreadonlydisabled-input

提问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

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

Knockout 的“attr”数据绑定确实支持这种情况,只需返回nullundefined从您的getDisabledState()函数中返回,它就不会发出该属性。

Demo Fiddle.

演示小提琴

回答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;
}
};

Source: https://github.com/knockout/knockout/issues/1100

来源:https: //github.com/knockout/knockout/issues/1100

回答by Frank Hiller

Knockout has an enablebinding as well as a disablebinding.

Knockout 有一个启用绑定和一个禁用绑定。

I'm not sure if these were available when the question was asked, but anyone referring back to this issue should be aware.

我不确定在提出问题时这些是否可用,但任何提到这个问题的人都应该知道。