【问题标题】:KnockoutJS radio button checked binding that works with JQuery Mobile 1.4?用于 JQuery Mobile 1.4 的 KnockoutJS 单选按钮检查绑定?
【发布时间】:2014-10-16 03:20:58
【问题描述】:

我一直在努力研究如何让检查绑定与 Knockout 和 JQuery Mobile 一起使用。由于某种原因,vanilla 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 knockout.js


    【解决方案1】:

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

    我尝试了这里的建议:http://codeclimber.net.nz/archive/2013/08/16/How-to-bind-a-jquery-mobile-radio-button-list-to.aspx,但没有成功 - 我怀疑它可能只适用于以前版本的 jQuery Mobile。

    这是我的替代方案:

    创建自定义绑定,根据隐藏复选框的选中状态切换标签上的“ui-radio-on”和“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>
    

    【讨论】:

    • 我想知道这是否有任何副作用,我将尝试它,因为似乎没有其他任何工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多