我刚刚开始使用 Knockout.js 并遇到了我的第一个绊脚石,尽管我不确定这是一个错误还是我没有做正确的事情。
当使用 css 绑定(bind)时,在应用多个类时的第一个条件,如果多个类名包含“-”,则只应用一个。在后续条件下不会发生这种情况,如果我从类名中删除“-”,则该类已成功应用。
fiddle :http://jsfiddle.net/pU9UR/
所以这是行不通的:
<i class="fa" data-bind=" css: { 'fa-caret-down text-info': active() && !asc(), 'fa-caret-up text-info': active() && asc(), 'fa-unsorted text-muted': !active() }">
而这样做:
<i class="fa" data-bind=" css: { 'fa-caret-down textinfo': active() && !asc(),'fa-caret-up text-info': active() && asc(), 'fa-unsorted text-muted': !active() }"></i>
这是一个错误还是我遗漏了什么?
编辑:
看来我最初的诊断是错误的,当我针对不同的条件重复同一类(class)时,就会出现问题。所以以下不起作用(仅应用 fa-caret-down
):
css: { 'fa-caret-down text-danger': active() && !asc(), 'fa-caret-up text-danger': active() && asc(), 'fa-unsorted text-muted': !active() }
但是这样做:
css: { 'fa-caret-down text-danger': active() && !asc(), 'fa-caret-up text-info': active() && asc(), 'fa-unsorted text-muted': !active() }
更容易看到的新 fiddle :http://jsfiddle.net/pU9UR/1/
最佳答案
这不是错误,而是 css
binding works 的特性:
The css binding adds or removes one or more named CSS classes to the associated DOM element.
因此,当 KO 遍历 css
绑定(bind)对象的所有属性时,它会执行以下操作:
- 获取
'fa-caret-down text-danger'
属性并检查表达式active() && !asc()
是否计算为 true 然后它添加新类fa-caret-down
和text-danger
- 采用
'fa-caret-up text-danger'
属性并检查表达式active() && asc()
,这与之前的表达式相反,因此它为 false,现在它删除现有类:它找不到fa-caret-up
但text-danger
存在,因此将其删除。
因此,要使其正常工作,您需要移出公共(public)部分以使用不同的条件:
<i class="fa" data-bind="css: {
'fa-caret-down': active() && !asc(),
'fa-caret-up': active() && asc(),
'fa-unsorted text-muted': !active(),
'text-danger': active }"></i>
演示 JSFiddle .
关于javascript - 具有重复类的 Knockout css 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21749085/