Javascript 单击鼠标时更改knockout.js 中的css 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11234920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:02:46  来源:igfitidea点击:

Changing css class in knockout.js on mouse click

javascriptjquerycssknockout.js

提问by Yasir

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

Knockout.js 文档显示了这样的 css 绑定:

<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?

我需要调整它以更改鼠标单击时的 css 类。我怎样才能做到这一点?

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?

但是,这并没有扩大选择列表的宽度。我究竟做错了什么?

回答by Pakman

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 clickand csson the same element. For example:

注意:您可以在同一个元素上组合clickcss。例如:

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

回答by daedalus28

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

最简单的方法是使用点击绑定来改变回调中的可观察对象。您将使用类似attr 绑定的方法适当地绑定类

回答by suman

I feel the problem is with script tag.

我觉得问题出在脚本标签上。

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

请在以下链接中找到解决方案:http: //jsfiddle.net/ZmU6g/3/