淘汰赛有条件地设置CSS [英] knockout set css conditionally

查看:97
本文介绍了淘汰赛有条件地设置CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉可能提出了不正确的问题,但我感到非常困惑.我需要根据项目属性的值在foreach循环中设置项目的css类.

Sorry for maybe uncorrect question, but I feel really confused. I need to set the css class of an item in a foreach loop based on the value of an item's property.

self.CssBind = ko.computed(function (task) {
    var CssBind = '';
    if (getComplexity(task) === 'Easy') {
     CssBind = "green";
 } else if (getComplexity(task) === 'Intermediate') {
     CssBind = 'yellow';}
 else if (getComplexity(task) === 'Difficult') {
     CssBind = 'red';
 }
 return CssBind;
});

我试图以这种方式获得复杂性,但是却没有定义....(在控制器中,有一种方法可以接受任务并返回复杂性)

I tried to get complexity in such way but have undefined.... (in controller there is method that accepts task and returns complexity)

self.complexity = ko.observable();
function getComplexity (task) {
    ajaxHelper(taskItem, 'GET').done(function (data) { self.complexity(data); });
};

在html中

<div class="panel panel-default" data-bind="foreach:{data:tasks, as: 'task'}">
        <div class="panel-heading">
          <a data-toggle="collapse" data-parent="#accordion" data-bind="text: Name, attr: { href : '#collapse' + task.Id}, css: {color: CssBind}">
          </a>
        </div>
        <div data-bind="attr: { id : 'collapse' + task.Id}" class="panel-collapse collapse">
            <div class="panel-body">
                <span data-bind="text: Name"></span>
            </div>
        </div>
    </div>

需要进行哪些更改才能使其正常工作?

What to change to make it work?

推荐答案

您的computed可能是在根视图模型上定义的,并且在调用它时,您已经在foreach: tasks范围内.您需要使用$root关键字指向CssBind.

Your computed is probably defined on the root view-model and when you're calling it you're already in a foreach: tasks scope. You need to use the $root keyword to point to CssBind.

此外,不需要computed,常规函数会更容易(尤其是通过参数传递):

Also, no need for a computed, regular function will do easier (especially with argument passing):

self.CssBind = function (task) {
    var CssBind = '';
    if (ko.unwrap(task.getComplexity) === 'Easy') {
     CssBind = "green";
 } else if (self.getComplexity() === 'Intermediate') {
     CssBind = 'yellow';}
 else if (self.getComplexity() === 'Difficult') {
     CssBind = 'red';
 }

 return CssBind;
});

在您的HTML中:

<a data-toggle="collapse"
   data-parent="#accordion"
   data-bind="text: Name, attr: { href : '#collapse' + task.Id}, style: {color: $root.CssBind.bind(null, task)}">

请注意,我将绑定处理程序从css更改为style(前者用于应用CSS类,而后者则应用显式CSS规则).

Please notice that I change the binding handler from css to style (the former is used to apply CSS classes while the latter applies explicit CSS rules).

这篇关于淘汰赛有条件地设置CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆