使用css绑定添加动态类

时间:2017-07-31 10:02:29

标签: css class magento knockout.js data-binding

我希望通过函数在payment-method后面添加一个带有knockout 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()"/>

该类由getCode()返回,其上面使用id和value。 所以我认为我可以做到:

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

但随后失败了:

  

knockout.js:2624 Uncaught SyntaxError:无法解析绑定。   绑定值:css:{&#39; _active&#39;:(getCode()== isChecked()),getCode()}   消息:意外的令牌}

<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课程,_active课程不再是初始设置。

如何设置该动态类?

3 个答案:

答案 0 :(得分:2)

这段代码是多余的,因为css data-bind正在用你的attr绑定覆盖。

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

这是你可以做动态类的方法(假设这些属性是可观察的):

<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);

答案 1 :(得分:0)

来自@tyler_mitchell的评论帮助我通过这个帖子找到了解决方案:https://stackoverflow.com/a/21528681/928666

我能做到:

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

不太好但很好......

答案 2 :(得分:0)

任何人都需要的另一个例子

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