简体   繁体   English

使用Knockout.js在列表中更改div的类

[英]Change class for a div in the list using Knockout.js

I am binding list of data few of which have image. 我绑定的数据列表中很少有图像。 I need to change the classes of div if the image value is NULL. 如果图像值为NULL,则需要更改div的类。

When image value is NULL, I need to change div classes Like, Delete,listcheckbox to ILike, Idelete, Ilistcheckbox or vice-versa. 当图像值为NULL时,我需要将div类(如Delete,listcheckbox)更改为ILike,Idelete,Ilistcheckbox,反之亦然。

How can I do it? 我该怎么做?

  <div data-role=view id="userProfile">
   <ul class="oneClass"  data-role="listview" id="Feeds-listview" data-bind="foreach:data">
   <li style="background-color:#FFF;white-space:normal">
  <div style="width:100%">
        <div data-bind="visible:ImageUrl">
     <img style="height: 200px;width: 300px;margin-top: 10px;" data-bind="attr: { src:ImageUrl }" />
    </div>

     <div data-bind="click:$root.Like" class="Like" >
 <div data-bind="click:$root.delete" class="delete"> </div> 
  <input type="checkbox" class="listcheckbox "/>
  </div>


    </li>
    </ul>
    <div>

 <style>
  .Like{
   }
  .delete{
   }
  .listcheckbox{
   }
  .ILike{
    }
  .Idelete{
  }
 .Ilistcheckbox{
   }

  </style>

You can make use of either css or style bindings. 您可以使用cssstyle绑定。 The css binding adds or removes one or more named CSS classes to the associated DOM element based on an expression. css绑定根据表达式向关联的DOM元素添加或删除一个或多个命名CSS类。 So, you can check if the expression for the ImageUrl is truthy or falsy and then apply the css accordingly. 因此,您可以检查ImageUrl的表达式是还是 ,然后相应地应用css。

Change code from 从更改代码

<div data-bind="click:$root.Like" class="Like" >
 <div data-bind="click:$root.delete" class="delete"> </div> 

To

<div data-bind="click:$root.Like, css: { Like: ImageUrl }" >
 <div data-bind="click:$root.delete, css: { delete: ImageUrl }"> </div> 

Working Code sample 工作代码示例

  var viewModel = { ImageUrl : null, ImageUrlNotEmpty : "value" }; ko.applyBindings(viewModel); 
 .Like{ background-color: yellow; } .delete{ background-color: green; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script> <div data-bind="css: { Like: ImageUrl }" >ImageUrl is empty Div 1</div> <div data-bind="css: { delete: ImageUrl }">ImageUrl is empty Div 2</div> <div data-bind="css: { Like: ImageUrlNotEmpty }" >ImageUrl is NOT empty Div 3</div> <div data-bind="css: { delete: ImageUrlNotEmpty }">ImageUrl is NOT empty Div 4</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM