KnockoutJS单选按钮检查了JQuery Mobile 1.4的绑定



我一直在努力研究如何让一个经过检查的绑定与Knockout和JQuery Mobile一起工作。由于某些原因,香草Knockout JS"检查"绑定不起作用:

<fieldset data-role="controlgroup">
    <legend>Your favorite flavor:legend>
    <input type="radio" name="flavor-selection" value="Chocolate" id="flavor-selection-chocolate" data-bind="checked: flavor" />
    <label for="flavor-selection-chocolate">Normal</label>
    <input type="radio" name="flavor-selection" value="Vanilla" id="flavor-selection-vanilla" data-bind="checked: flavor" />
    <label for="flavor-selection-vanilla">Party</label>
</fieldset>

有什么想法吗?

事实证明,jQuery Mobile为单选按钮设置标签样式,以便显示单选选择(隐藏实际的单选按钮本身)。

我尝试了一下这里的建议:http://codeclimber.net.nz/archive/2013/08/16/How-to-bind-a-jquery-mobile-radio-button-list-to.aspx但没有取得任何成功——我怀疑它可能只适用于jQueryMobile的前一个版本。

这是我的选择:

根据隐藏复选框的选中状态,创建一个自定义绑定来切换标签上的"ui radio on"one_answers"ui radio-off"类:

ko.bindingHandlers.jqMobileRadioChecked = {
    init: function (element, valueAccessor, allBindingsAccessor, data, context) {
        ko.bindingHandlers.checked.init(element, valueAccessor, allBindingsAccessor, data, context);
    },
    update: function (element, valueAccessor, allBindingsAccessor, data, context) {
        var viewModelValue = valueAccessor();
        var viewModelValueUnwrapped = ko.unwrap(viewModelValue);
        var $el = $(element);
        var $label = $el.siblings("label[for='" + $el.attr("id") + "']");
        if (viewModelValueUnwrapped === $el.val()) {
            $label.removeClass("ui-radio-off");
            $label.addClass("ui-radio-on");
        } else {
            $label.removeClass("ui-radio-on");
            $label.addClass("ui-radio-off");
        }
    }
};

然后HTML就变成了:

<fieldset data-role="controlgroup">
    <legend>Your favorite flavor:legend>
    <input type="radio" name="flavor-selection" value="Chocolate" id="flavor-selection-chocolate" data-bind="jqMobileRadioChecked: flavor" />
    <label for="flavor-selection-chocolate">Normal</label>
    <input type="radio" name="flavor-selection" value="Vanilla" id="flavor-selection-vanilla" data-bind="jqMobileRadioChecked: flavor" />
    <label for="flavor-selection-vanilla">Party</label>
</fieldset>

最新更新