添加动态 class 与 css 绑定

add dynamic class with css binding

我想在 payment-method 后面添加一个 class 通过函数与敲除 css 绑定(在 Magento 2.1 中)。 所以这是当前代码:

<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}">
    <div class="payment-method-title field choice">
        <input type="radio"
               name="payment[method]"
               class="radio"
               data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()"/>

class 由 getCode() 返回,上面使用 id 和值。 所以我想我可以这样做:

<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked()), getCode()}">

但后来失败了:

knockout.js:2624 Uncaught SyntaxError: Unable to parse bindings. Bindings value: css: {'_active': (getCode() == isChecked()), getCode() } Message: Unexpected token }

<div class="payment-method" data-bind="css: getCode()">

这有效。

<div class="payment-method" data-bind="css: {getCode()}">

这不是。

<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}, attr: {'class': getCode()}">

这也有效,但会覆盖 payment-method class 并且 _active class 最初也不再设置。

如何设置动态 class?

这段代码是多余的,因为 css 数据绑定正在被您的 attr 绑定覆盖。

<div class="payment-method" data-bind="css: {'_active': (getCode() == isChecked())}, attr: {'class': getCode()}">

这就是您可以执行动态 class 的方式(假设这些属性是可观察的):

<div class="payment-method" data-bind="css: CSS">

self.CSS = ko.computed(function() {
    var code = self.getCode();
    var isChecked = self.isChecked();
    return code + ' ' + (code == isChecked ? '_active' : '');
}, viewModel);

@tyler_mitchell 的评论帮助我通过这个帖子找到了自己的解决方案:

我能做到:

<div class="payment-method" data-bind="attr: { 'class': 'payment-method ' + getCode() }, css: {'_active': (getCode() == isChecked())}">

不是很出色,但很好...

另一个例子应该有人需要它

<div data-bind="attr: { 'class': 'mainClass' + (dynamicClassSetOnce ? ' ' + dynamicClassSetOnce : '' }, css: { 'mainClass--focussed': isFocussed }">
...
</div>