2

jQuery 1.9.1、jQM 1.3、およびノックアウト 2.2.1 を使用しています。

私のhtmlは次のとおりです。

<div data-role="page" id="coloursView">
    <div data-role="content">
        <fieldset data-role="controlgroup">
            <legend>Colour:</legend>
            <input type="radio" name="colours" data-bind="checked: colour" id="radio-1" value="1" />
            <label for="radio-1">Red</label>
            <input type="radio" name="colours" data-bind="checked: colour" id="radio-2" value="2" />
            <label for="radio-2">Blue</label>
            <input type="radio" name="colours" data-bind="checked: colour" id="radio-3" value="3" />
            <label for="radio-3">Green</label>
        </fieldset>
    </div><!--/content -->
</div><!--/page -->

私のビュー モデルも非常に単純です。

function ColoursViewModel() {
  this.template = "coloursView";
  this.colour = ko.observable("1");
  this.label = ko.observable(); // custom binding
}

ここで、値ではなく、選択した色の説明を取得したいと思います。次のようなカスタムバインディングが必要だと私には思えます:

ko.bindingHandlers.label = {
    update: function(element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $("radio", element).filter(function(el) { return $(el).text() === value; }).prop("checked", "checked");
    }
};

しかし、関連するラベルのテキスト、つまりラベルのテキストを取得できません。

誰かが助けることができますか?前もって感謝します

4

2 に答える 2

1

アップデート

アイテムのみを検索し、テキスト内の空白:checkedを削除する別のアプローチを次に示します。

チェックボックス

$('input[type=checkbox]').each(function () {
 if ($(this).is(':checked')) {
  var checkbox = $(this).prev('label').text();
  alert('Checkbox: ' + checkbox.replace(/\s+/g, ' '));
 }
});

無線

$('input[type=radio]').each(function () {
 if ($(this).is(':checked')) {
  var radio = $(this).prev('label').text();
  alert('Radio: ' + radio.replace(/\s+/g, ' '));
 }
});

更新されたデモ


チェックボックス

$('div.ui-checkbox').find('span.ui-btn-text').text();

無線

$('div.ui-radio').find('span.ui-btn-text').text();
于 2013-04-23T00:02:09.790 に答える