分类Knockout js选择框

Categorizing Knockout js selection box

本文关键字:选择 js Knockout 分类      更新时间:2023-12-22

假设我有下面的knockoutjs绑定


var optionsWithCategory = [
  "Category: Person", // Category option should be disabled, or non-selectable
  "Jason",
  "John",
  "Category: Department",
  "Human Resource",
  "Sales"
];
<div id="selectBox">
<select databind="options: optionsWithCategory"></select>
</div>

我可以采取哪些方法将disable="disable"添加到所有具有以Category:开头的文本值的options DOM元素中。因此,PersonDepartment实际上是不可选择的,但在选择框中充当分隔符。此外,select框会动态添加到selectBoxdiv元素中。

我想到的一个方法是:

$('#selectBox').bind('DOMNodeInserted', function (e) {
    if (e.target.text != undefined && e.target.text.indexOf(':') >= 0) {
        $(e.target).attr("disabled", "disabled");
    }
});

但它看起来不太优雅,还有其他办法吗?

我不确定有什么干净的方法可以做到这一点,因为的使用有点不常见

但是,您可以执行与编写的代码类似的代码,也可以创建自己的绑定处理程序来执行此操作。我建议使用绑定处理程序,因为它将把所有逻辑封装在一个地方。