Как найти текст в метке для jQuery Mobile Radio и Checkbox с нокаутом?

Я использую 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");
    }
};

Но я не могу получить текст соответствующей метки - метку для текста.

Кто-то может помочь? заранее спасибо

2 ответа

Решение

Извините, если я отвечу сам, но я думаю, что получил это. По крайней мере, для радиовходов.

Теперь у меня есть собственный обработчик привязки на уровне набора полей, чтобы разметка оставалась чистой и более читаемой, как я могу:

<fieldset data-role="controlgroup" id="front-colours" data-bind="frontColourLabel: frontColour">
    <legend>Front Colour: <span data-bind="text: frontColourDescription"></span> (Value: <span data-bind="text: frontColour"></span>)</legend>
    <input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-1" value="red" />
    <label for="fc-radio-1">Red</label>
    <input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-2" value="blue" />
    <label for="fc-radio-2">Blue</label>
    <input type="radio" name="front-colours" data-bind="checked: frontColour" id="fc-radio-3" value="green" />
    <label for="fc-radio-3">Green</label>
</fieldset>

это обработчик привязки, который я придумаю:

ko.bindingHandlers.frontColourLabel = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
        ko.utils.unwrapObservable(valueAccessor()); 
        var id = $('input:radio[name='+element.id+']:checked').prop("id");
        var radioText = $('label[for=' + id + ']').text();
        viewModel.frontColourDescription(radioText);
    }
};

Единственная сложность здесь в том, что id набора полей равен названию радиогруппы, так как легко отфильтровать, к какой радиогруппе я хочу обратиться.

ПРИМЕР РАБОТЫ : http://jsfiddle.net/h7Bmb/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();
Другие вопросы по тегам