2016-09-30 47 views
1

我想基於當前選定的單選按鈕應用使用數據綁定的CSS樣式。基於在Knockoutjs中選擇的單選按鈕應用CSS樣式類綁定

下面是我嘗試應用的代碼,但不工作..

<input type="radio" value="mtn" data-bind="checked: setRadioVal, css: {lblstylebold: checkRadioEnabled(this)}" id="mtnradio"> 
    <input type="radio" value="atn" data-bind="checked: setRadioVal, css: {lblstylebold: checkRadioEnabled(this)}" id="atnradio"> 

var ViewModel = { 
    setRadioVal: ko.observable(null), 
    checkRadioEnabled: function(value) { 
    if (value == ViewModel.setRadioVal()) 
    return true; 
    else 
    return false; 
    } 
} 
ViewModel.setRadioVal("mtn") // This gets sets initially with either mtn or atn based on ajax response which I have not posted here. Just for understanding I have set as mtn. 

因此,一旦用戶選擇了單選按鈕之一,setRadioVal獲取與MTN無論ATN或更新。我試圖調用函數checkRadioEnabled,並且當所選的當前單選按鈕值等於啓用值時返回true。但css類沒有得到應用。

當我調試時,我看到它在功能checkRadioEnabled裏面單擊單選按鈕時,但值參數作爲窗口對象來。如何傳遞單選按鈕值並在函數內部訪問它checkRadioEnabled? 我在這裏做錯了什麼?

回答

1

這裏是一個小提琴http://jsfiddle.net/LkqTU/31964/

<input type="radio" 
     class="enabled" 
     name="flavorGroup" 
     value="mtm" 
     data-bind="checked: selectedValue" /> 
    <span data-bind="css: { enabled: selectedValue() === 'mtm' }">mtm</span> 
    <input type="radio" 
    name="flavorGroup" 
    value="atm" 
    data-bind="checked: selectedValue" /> 
    <span data-bind="css: { enabled: selectedValue() === 'atm' }">atm</span> 

JS

function model() { 
    var self = this; 
    selectedValue = ko.observable("atm") 
} 

var mymodel = new model(); 

$(document).ready(function() { 
    ko.applyBindings(mymodel); 
}); 
+0

抱歉耽擱在接受和感謝您的回答! –