Changing css class in knockout.js on mouse click

99封情书 提交于 2019-12-21 07:27:29

问题


The knockout.js documentation shows the css binding like this:

<div data-bind="css: { profitWarning: currentProfit() < 0 }">   
    Profit Information
</div>

I need to adapt it to change the css class on mouseclick. How can I do this?

Based on answers below, I am using some code like this:

// CSS class to be applied
<style>
    .bigclass
    {
        width: 200px;
    }

</style>

// Select list inside a jquery .tmpl
<script id='criteriaRowTemplate' type='text/html'>
    <tr>
        <td>
            <select data-bind='click: makeBig, css: {bigclass : SelectHasFocus() > 0}' />
        </td>
    </tr>
</script> 

// Knockout.js Viewmodel
var CriteriaLine = function() {
    this.SearchCriterion = ko.observable();
    this.SelectHasFocus = ko.observable(0);

    // this method is called
    makeBig = function(element) { 
        this.SelectHasFocus(1);            
    };        
};

However, this is not expanding the width of the select list. What am I doing wrong?


回答1:


Have your click function change an observable variable. For example:

<div data-bind="css: { myclass: newClass() == true }">
   Profit Information
</div>

<button data-bind="click: changeClass">Change Class</button>

<script type="text/javascript">
    var viewModel = {
        newClass: ko.observable(false),
        changeClass: function() {
            viewModel.newClass(true);
        }
    }; 
</script>

Note: You can combine click and css on the same element. For example:

<div databind="click: changeClass, css: { myclass: newClass() == true }"></div>



回答2:


I feel the problem is with script tag.

Please find the solution in following link: http://jsfiddle.net/ZmU6g/3/




回答3:


The simplest way is to use a click binding which changes an observable in the callback. You would bind the class appropriately using something like the attr binding



来源:https://stackoverflow.com/questions/11234920/changing-css-class-in-knockout-js-on-mouse-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!