gpt4 book ai didi

javascript - Knockout.js 在使用 'options' 绑定(bind)时更改

转载 作者:数据小太阳 更新时间:2023-10-29 05:33:48 25 4
gpt4 key购买 nike

在选择列表上使用“选项”绑定(bind)时,是否可以更改选择列表选项元素的样式(使用“样式”或“css”绑定(bind))?或者这只能通过在选择列表上使用“foreach”并更改每个样式来完成吗?

我在代码中有这个:

<select id="components-select" size="4" name="components-select"
data-bind=" options: combinedComponents,
optionsText: 'displayName',
optionsValue: 'id',
value: chosenComponent"></select>

但是如果我附加 style: {color: isDefault() === true ? 'black' : 'red'} 如果 isDefault 返回 false,则整个列表为红色。

以这种方式编码是实现此目标的唯一方法:

<select id="components-select" size="4" name="components-select"
data-bind="foreach: combinedComponents">
<option data-bind="value: id, text: displayName, style: {color: isDefault() === true ? 'black' : 'red'}"></option>
</select>

或者是否存在我不知道的某种形式的 Knockout.js 魔法?

谢谢!

最佳答案

为了扩展 Thomas Wiersema 的回答,您希望按行处理该问题的方式类似于:

<select id="components-select" size="4" name="components-select"
data-bind="foreach: combinedComponents">
<option data-bind="value: id, text: displayName, style: {color: getColorFor.call(null, $data) }"></option>
</select>

然后,在 JavaScript 中,像这样将一个函数附加到您的父对象(当然,我做了一些假设,例如您的父对象被称为 vmisDefault 属于一个 combinedComponent):

vm.getColorFor = function(component) {
return component.isDefault() === true ? 'black' : 'red';
}

如果您不确定 call 的作用,请查看 bind vs apply vs call

希望对您有所帮助 - 如果我可以详细说明,请告诉我!

关于javascript - Knockout.js 在使用 'options' 绑定(bind)时更改 <option> 的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15956735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com