【问题标题】:Data-bind style not working with if else condition数据绑定样式不适用于 if else 条件
【发布时间】:2015-06-14 02:54:05
【问题描述】:

我正在尝试根据我从 js 文件中获取的值更改 div 的背景。

因此,如果该值与 0 不同,我想要一个背景,如果它为 0,我想要另一个背景。

这是我正在尝试的标记:

<tbody data-bind="foreach: skills">
    <tr>
        <td>
            <div data-bind="attr: { id: Id }, style: { background: Outstanding != '0' ? 'none repeat scroll 0 0 #B33A3A;' : 'none repeat scroll 0 0 #396eac;' }">
                <span data-bind="text: Name" style="color: #ffffff;"></span>
            </div>
            <div>
                <span data-bind="visible: Outstanding != '0', text: Outstanding + ' Needed'" style="color: #365474"></span><br/> 
                <span data-bind="text: Employees" style="color: #365474"></span>
            </div>
        </td>
    </tr>
</tbody>

你们看到这里有什么不正确的地方吗?

PS。使用 Chrome 插件 Knockoutjs 上下文调试器,我可以看到 Outstanding 的实际值为 0:

【问题讨论】:

    标签: javascript jquery css knockout.js knockout-2.0


    【解决方案1】:

    背景值末尾有不必要的分号 (;)。 将行更改为:

    <div data-bind="attr: { id: Id }, style: { background: Outstanding != '0' ? 'none repeat scroll 0 0 #B33A3A' : 'none repeat scroll 0 0 #396eac' }">
    

    这应该可以解决它。

    请看下面的例子:

    (function() {
        'use strict';
        
        function MyVM() {
            var self = this;
            self.skills = ko.observableArray([
                { Id: 1, Outstanding: '0', Name: 'Foo', Employees: 'Person A' },
                { Id: 2, Outstanding: '1', Name: 'Bar', Employees: 'Person B' }
            ]);
            
            
        }
        
        ko.applyBindings(new MyVM(), document.body);
    }());
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    <table>
        <tbody data-bind="foreach: skills">
            <tr>
                <td>
                    <div data-bind="attr: { id: Id }, style: { background : Outstanding !== '0' ?  'none repeat scroll 0 0 #B33A3A' : 'none repeat scroll 0 0 #396eac' }">
                        <span data-bind="text: Name" style="color: #ffffff;"></span>
                    </div>
                    <div>
                        <span data-bind="visible: Outstanding != '0', text: Outstanding + ' Needed'" style="color: #365474"></span><br/> 
                        <span data-bind="text: Employees" style="color: #365474"></span>
                    </div>
                </td>
            </tr>
        </tbody>
    </table>

    【讨论】:

    • 如果模型实际上不是字符串,可能需要小心那个出色的比较。我不知道你的数据结构,但万一它是一个数字,它可能会有问题。也许将它按摩成一个布尔值......
    • 使用 != 而不是 !== 将匹配数字 0 和 '0' 字符
    猜你喜欢
    • 2013-11-12
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-05
    相关资源
    最近更新 更多